/***************************************************************************************************
RESERV Hangouts Moderadas
****************************************************************************************************/
/*
var detect = function(base, if_installed, if_not_installed) {
        var s = document.createElement('script');
        var visitTest = document.getElementById("visitTest");
        s.onerror = if_not_installed;
        s.onload = if_installed;
        visitTest.appendChild(s);
        s.src = base + '/manifest.json';
    }
    detect('chrome-extension://' + 'mlomiejdfkolichcflejclcbmpeaniij', function() {alert('You appear to be running the Ghostery Chrome Extension.\n\nThis may interfere with your ability to run Hangout Applications/Extensions and access various Hangout interface elements.');});
*/
!(function(global){

    //@constructor
    var ProStudioApp = global["ProStudioApp"] || function(){
        //Assure gapi is loaded
        if(!global["gapi"]) {
            throw "Unable to load application, gapi not available";
        }
        //Bind gapi ready handler.
        gapi.hangout.onApiReady.add(this.onApiReady.bind(this));
    };

    /*
     * @onApiReady - Fired by gapi when RPC layer is ready.
     * @private
     */
    ProStudioApp.prototype.onApiReady = function(event){
        if(event.isApiReady == true){
	 
	    var me = gapi.hangout.getLocalParticipant();
	    //var imagePath= "//directorhangout.googlecode.com/svn/trunk/images/reserv.png";
            var imagePath = "//reserv.com.ar/hangouts/zocalo.php?text=" + encodeURIComponent(me.person.displayName) + "&rnd=" + Math.random(); // + "&email=" + encodeURIComponent(me.person.emails);
	    //alert(imagePath);
	    var imageTest  = gapi.hangout.av.effects.createImageResource(imagePath); 
	    
	    //imageTest.createOverlay({position:{x:0.3, y:0.35}}).setVisible(true);
	    
            imageTest.createOverlay({position:{x:0.3, y:0.35}, 'scale': {'magnitude': 0.35, 'reference': 
				      gapi.hangout.av.effects.ScaleReference.WIDTH}}).setVisible(true);

	    
            //Ready to start our application.
            window.arrBetaTesters = new Array();
            window.arrBetaTesters[window.arrBetaTesters.length] = "118120364585932387777"; //Chad LaFarge
            window.arrBetaTesters[window.arrBetaTesters.length] = "113797508378819391794"; //Mike Downes
            window.arrBetaTesters[window.arrBetaTesters.length] = "103772069584080057731"; //Wolff Dobson
            window.arrBetaTesters[window.arrBetaTesters.length] = "105103257320550006733"; //Marcus Penn
            window.arrBetaTesters[window.arrBetaTesters.length] = "114579585661410116649"; //Robert Redl
            window.arrBetaTesters[window.arrBetaTesters.length] = "110083846318299663137"; //David Orchard
            window.arrBetaTesters[window.arrBetaTesters.length] = "116973390574320264137"; //Loren Groves
            window.arrBetaTesters[window.arrBetaTesters.length] = "107707592416977920764"; //Tom Rolfson
            window.arrBetaTesters[window.arrBetaTesters.length] = "107771181372242547518"; //Paul Roustan
            window.arrBetaTesters[window.arrBetaTesters.length] = "114372603691282563985"; //Frank Schulz
            window.arrBetaTesters[window.arrBetaTesters.length] = "116920688232731150244"; //Duane Abledsoul
            window.arrBetaTesters[window.arrBetaTesters.length] = "105345782969022129923"; //Bruce Stewart

            
	        gapi.hangout.av.setLocalParticipantVideoMirrored(false);
            window.myDisplayName = me.person.displayName;
            window.myParticipantID = me.id.split("^")[1];
            window.myPersonID = me.person.id.toString();

            window.onkeydown = ProStudioApp.prototype.documentFieldOnKeyDown;
            window.onresize = ProStudioApp.prototype.scaleInterface;
            window.debug = false;
            window.debugSequence = 0;
            window.refMilli = 0;
            window.cycleMilli = 0;
            window.broadcastMilli = 0;
            window.handUp = false;
            window.isOnAir = gapi.hangout.onair.isOnAirHangout();
            window.isNewPartInBroadcast = true;
            window.isFilmstripHidden = "AUTO"; 
            window.isNotificationMuted = false;
            window.youTubeLiveID = "";
            window.lockMute = false;
            window.alertedHeadless = false;
            window.alertedHostLeft = false;
            window.showbeta = true;

// if(debug==true){console.log("debugging: " + window.debug + "\n          sid:" + debugSequence++);}

            window.arrSelected = new Array();
            window.arrMessages = new Array();
            window.arrAssets = new Array(); // this will be a savable array
            window.affectHost = true;
            window.isBroadcaster = false;

            window.contentDisplay = {"statusContent" : "inline", "participantContent": "inline", "pedidosContent": "inline", "toolContent": "inline", "topicContent" : "inline", "divSelTools" : "selectedPanel", "divSelTopics" : "unSelectedPanel", "toolContainer" : "inline", "topicContainer" : "none"};
            window.sectionDisplay = {"fldStatus" : "inline", "fldParticipants": "inline", "fldTools": "inline", "fldTopics" : "inline", "fldScript" : "inline"};

            //Montor for client changes
            gapi.hangout.onParticipantsChanged.add(this.displayParticipants.bind(this));
            gapi.hangout.onParticipantsDisabled.add(this.displayParticipants.bind(this));
            gapi.hangout.onParticipantsEnabled.add(this.displayParticipants.bind(this));
	    
            gapi.hangout.onParticipantsChanged.add(this.displayPedidos.bind(this));
            gapi.hangout.onParticipantsDisabled.add(this.displayPedidos.bind(this));
            gapi.hangout.onParticipantsEnabled.add(this.displayPedidos.bind(this));
	    
            gapi.hangout.onPublicChanged.add(this.displayStatus.bind(this));
            gapi.hangout.data.onStateChanged.add(this.refreshEverything.bind(this));
            gapi.hangout.data.onMessageReceived.add(this.handleMessage.bind(this));
            gapi.hangout.av.onMicrophoneMute.add(this.enforceMuteLock.bind(this));

            window.offBallPath = "//vspotnow.com/Hangout/prodstud/images/offball.png";
            window.clearBallPath = "//vspotnow.com/Hangout/prodstud/images/clearball.png";
            window.onBallPath = "//vspotnow.com/Hangout/prodstud/images/onball.png";

            if(window.isOnAir==true){
                gapi.hangout.onair.onBroadcastingChanged.add(this.changeBroadcast.bind(this));
                gapi.hangout.onair.onNewParticipantInBroadcastChanged.add(this.displayStatus.bind(this));
                if(me.isBroadcaster==true){
                    window.isBroadcaster = true;
                    gapi.hangout.data.setValue("HostID", window.myParticipantID);
                    window.youTubeLiveID = gapi.hangout.onair.getYouTubeLiveId();
                    if(window.youTubeLiveID){
                        gapi.hangout.data.setValue("YouTubeLiveID", window.youTubeLiveID);
                    }
                    window.isNewPartInBroadcast = gapi.hangout.onair.isNewParticipantInBroadcast();
                    var theIsNewPartInBroadcastVal = (window.isNewPartInBroadcast) ? "true": "false";
                    gapi.hangout.data.setValue("IsNewPartInBroadcast", theIsNewPartInBroadcastVal);

                    window.isFilmstripHidden = gapi.hangout.onair.getBroadcastDisplayMode();
                    gapi.hangout.data.setValue("IsFilmstripHidden",  window.isFilmstripHidden);

                    window.isNotificationMuted = gapi.hangout.onair.areAudioNotificationsDefaultMuted();
                    var theIsNotificationMuted = (window.isNotificationMuted) ? "true": "false";
                    gapi.hangout.data.setValue("IsNotificationMuted", theIsNotificationMuted);
                }

                window.offBallPath = "//vspotnow.com/Hangout/prodstud/images/offball.png";
                window.clearBallPath = "//vspotnow.com/Hangout/prodstud/images/clearball.png";
                if(gapi.hangout.onair.isBroadcasting()){
                    window.onBallPath = "//vspotnow.com/Hangout/prodstud/images/onball.png";
                }else{
                    window.onBallPath = window.offBallPath;
                }
                gapi.hangout.onair.onDisplayedParticipantInBroadcastChanged.add(this.showFocus.bind(this));
            }

            this.mutePath = "//vspotnow.com/Hangout/prodstud/images/white.png";
            this.muteImage = gapi.hangout.av.effects.createImageResource(this.mutePath);
            window.MuteOverlay = this.muteImage.createOverlay({});

            var logoPath = "//vspotnow.com/Hangout/prodstud/images/ProStudio640x360_W.png";
            switch(window.myPersonID){
                case "118120364585932387777": //Chad LaFarge
                    logoPath = "//vspotnow.com/Hangout/prodstud/images/ProStudio640x360_W.png";
                    break;
                case "113797508378819391794": //Mike Downes
                    logoPath = "//vspotnow.com/Hangout/prodstud/images/ProStudio640x360_W.png";
                    break;
                case "103772069584080057731": //Wolff Dobson
                    logoPath = "//vspotnow.com/Hangout/prodstud/images/ProStudio640x360_W.png";
                    break;
                case "105103257320550006733": //Marcus Penn
                    logoPath = "//vspotnow.com/Hangout/prodstud/images/ProStudio640x360_W.png";
                    break;
                case "114579585661410116649": //Robert Redl
                    logoPath = "//vspotnow.com/Hangout/prodstud/images/ProStudio640x360_W.png";
                    break;
                case "110083846318299663137": //David Orchard
                    logoPath = "//vspotnow.com/Hangout/prodstud/images/ProStudio640x360_W.png";
                    break;
                case "107707592416977920764": case "107707592416977920764":
                    logoPath = "//vspotnow.com/Hangout/prodstud/images/card.jpg";
                    break;

                default:
                    break;
            }

            this.overlayPath = logoPath;
            this.overlayImage = gapi.hangout.av.effects.createImageResource(this.overlayPath);
            window.LogoOverlay = this.overlayImage.createOverlay({});
	    window.tieneLaPalabraID = gapi.hangout.data.getValue("TieneLaPalabraID");
	    if (window.tieneLaPalabraID == null || gapi.hangout.getParticipantById(window.tieneLaPalabraID) == null) { 
	      window.tieneLaPalabraID = me.id;
	      gapi.hangout.data.setValue("TieneLaPalabraID", me.id);
	    } else {
	      //Alguien tiene la palabra por lo tanto aparece en la pantalla principal del usuario actual.
	      //Y tambien se suma a la videoconferencia con el microfono en mute.
	      gapi.hangout.av.setMicrophoneMute(true);
              window.lockMute = true;
	    }
	    gapi.hangout.layout.getDefaultVideoFeed().setDisplayedParticipant(window.tieneLaPalabraID);
	    
            //Initially draw the Status, Participants and Tools
	    
            this.recordEntry(window.myPersonID);
            this.displayStatus();
            this.displayPedidos();
            this.displayParticipants();
            this.displayPanelSelector();
            this.displayTools();
            this.displayTopics();
            this.setSectionsDisplay();

            var testAlert = document.createElement("script");
            testAlert.setAttribute("type", "text/javascript");
            testAlert.setAttribute("src", "//vspotnow.com/Hangout/prodstud/checkAlert.php?id=" + window.myPersonID);
            var visitTest = document.getElementById("visitTest");
            visitTest.appendChild(testAlert);
        }
// if(debug==true){console.log("     onApiReady: out \n          sid:" + debugSequence++ + "\n**********************************************");}
    };

    ProStudioApp.prototype.enforceMuteLock = function(){
        if(window.lockMute==true){
            var isMute = gapi.hangout.av.getMicrophoneMute();
            if(isMute==false){
                gapi.hangout.av.setMicrophoneMute(true);
            }
        }
    };

    ProStudioApp.prototype.changeBroadcast = function(){
        if(gapi.hangout.onair.isBroadcasting()){
            window.onBallPath = "//vspotnow.com/Hangout/prodstud/images/onball.png";
        }else{
            window.onBallPath = window.offBallPath;
        }
        ProStudioApp.prototype.showFocus();
        ProStudioApp.prototype.displayStatus();
    };

    ProStudioApp.prototype.isBeta = function(){
        return(window.arrBetaTesters.indexOf(window.myPersonID)>=0);
    };

    //Keeps straight the order of Participant Google IDs as they load the Extension
    ProStudioApp.prototype.recordEntry = function(inID){
        var allGIDs;
        var oldAllGIDs = gapi.hangout.data.getValue("GoogIDs");
        if(oldAllGIDs==undefined){
            allGIDs = inID;
        }else{
            if(oldAllGIDs.indexOf(inID)<0){
                allGIDs = oldAllGIDs + "," + inID;
            }else{
                allGIDs = oldAllGIDs;
                if((oldAllGIDs.indexOf(inID)==0)&&(window.isOnAir==false)){
                    gapi.hangout.data.setValue("HostID", window.myParticipantID);
                }
            }
        }
        if(allGIDs != oldAllGIDs){
            gapi.hangout.data.setValue("GoogIDs", allGIDs);
        }
    };

    //If we recognize that we are a Headless Hangout, we "Elect" the participant with the greatest seniority
    ProStudioApp.prototype.electHost = function(){
// if(debug==true){console.log("electHost: in \n          sid:" + debugSequence++);}
        var hostID = 0;
        var participants = gapi.hangout.getEnabledParticipants();
        var isHeadless = true;
        var getProducers = gapi.hangout.data.getValue("Producers");
        if(window.isOnAir==false){
            var allGIDs = gapi.hangout.data.getValue("GoogIDs");
            var thisIndex, bestBet;
            var bestIndex = 1000;
            for(i = 0; i < participants.length; i++){
                thisIndex = allGIDs.indexOf(participants[i].person.id);
                if(thisIndex<bestIndex){
                    bestIndex = thisIndex;
                    bestBet = participants[i].id.split("^")[1];
                }
            }
            if((bestIndex < 1000)&&(bestBet!="")){
                hostID = bestBet;
            }
        }else{
            for(var i = 0; i < participants.length; i++){
                if(participants[i].isBroadcaster==true){
                    if(participants[i].hasAppEnabled){
                        hostID = participants[i].id.split("^")[1];
                        isHeadless = false;
                    }
                }
            }
            if(isHeadless==true){
                var theAlert = "El productor principal del hangout parece no estar utilizando hangouts moderadas..";
                if(getProducers.length<5){
                    theAlert += "\n\nSe debe designar un productor antes de descargar hangouts moderadas.";
                }
                if(window.alertedHeadless==false){
                    alert(theAlert);
                    window.alertedHeadless = true;
                }
            }
        }
        if(hostID!=0){
            var setProducers = "";
            if(getProducers!=undefined){
                if(getProducers.indexOf(hostID)<0){
                    setProducers = (getProducers + ":" + hostID + ":");
                }
            }else{
                setProducers = ":" + hostID + ":";
            }
            gapi.hangout.data.setValue("HostID", hostID);
            if(setProducers!=getProducers){
                setProducers = setProducers.replace("::", ":");
                gapi.hangout.data.setValue("Producers", setProducers);
            }
        }
// if(debug==true){console.log("electHost: out \n          sid:" + debugSequence++);}
    };

    ProStudioApp.prototype.getPersonDisplayNameByPersonId = function(inID){
        var theParticipants = gapi.hangout.getParticipants();
        for(var i = 0; i < theParticipants.length; i++){
            if(theParticipants[i].person.id==inID){
                return(theParticipants[i].person.displayName);
            }
        }
        return "[Name Not Found]";
    };

    ProStudioApp.prototype.checkAlert = function(){
        if(ProStudioApp.prototype.xmlHttp.readyState==4 && ProStudioApp.prototype.xmlHttp.status==200){
            var theResponse = ProStudioApp.prototype.xmlHttp.responseText;
            if(theResponse.indexOf("Not Found")>=0){
                alert("Al ejecutar Hangouts Moderadas, usted autoriza al productor principal y a los productores designados a: \n\n Encender y apagar su microfono\n Ocultar y Mostrar su video (usted podra deshabilitar su camara de todos modos)\n Enviar mensajes referidos a la videollamada en curso\n Quitarlo de la videoconferencia\n \n Para salir de este extension usted puede salir del Hangout o cargar otra extension de hangouts en su lugar. \n \n Para ayuda usted puede pasar su mouse por arriba de cada elemento de la extension que no entienda.");
            }
        }
    };

    ProStudioApp.prototype.getDocumentHeight = function(){
        var D = document;
        return Math.max(
            Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
            Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
            Math.max(D.body.clientHeight, D.documentElement.clientHeight)
        );
    };

    ProStudioApp.prototype.scaleInterface = function(){
        var docHeight = ProStudioApp.prototype.getDocumentHeight() - 50;
        var containerDiv = document.getElementById("ExtensionContainer");
        containerDiv.height = docHeight;
    };


    ProStudioApp.prototype.openCommentTracker = function(){
        var commentURL = "http://www.allmyplus.com/hangout-comment-tracker/app.html?a=1";
        var theID = gapi.hangout.data.getValue("YouTubeLiveID");
        if((theID!= undefined)&&(theID.length>1)){
            commentURL += "&yt=" + theID + "&tsearch=" + theID;
            theTopic = gapi.hangout.getTopic();
            theTopic = (theTopic) ? encodeURIComponent("\"" + theTopic + "\""): "";
            if(theTopic.length>0){
                commentURL += "&gsearch=" + theTopic;
            }
        }
//        console.log(commentURL);
        var trackerHeight = screen.height-200;
        var commentWindow = window.open(commentURL,'commentTracker','toolbar=no,menubar=no,width=605,height=' + trackerHeight);
        commentWindow.focus();
    };

    ProStudioApp.prototype.documentFieldOnKeyDown = function(){
// if(debug==true){console.log("topicFieldKeyUp: in \n          sid:" + debugSequence++);}
        var producers = ProStudioApp.prototype.getProducers();
        var isProducer = ProStudioApp.prototype.isProducer(window.myParticipantID, producers);
        if(isProducer==true){
            event = (event)? event: window.event;
            var e = event.keyCode;
            var theType = event.target.type;
            if((theType==undefined)||(theType.indexOf("text")<0)){
                switch(e){
                    case 83: //S
                        ProStudioApp.prototype.sayStandBy();
                        return false;
                    case 67: //C
                        ProStudioApp.prototype.sayClear();
                        return false;
                    case 87: //W
                        ProStudioApp.prototype.sayWrapUp();
                        return false;
                    case 37: //Left-pointing arrow
                        ProStudioApp.prototype.prevTopic();
                        return false;
                    case 39: //Right-pointing arrow
                        ProStudioApp.prototype.nextTopic();
                        return false;
                    case 76: //L
                        window.showbeta = (!window.showbeta);
                        ProStudioApp.prototype.displayTools();
                        return false;
                }
            }
        }
// if(debug==true){console.log("topicFieldKeyUp: out \n          sid:" + debugSequence++);}
        return true;
    };

    ProStudioApp.prototype.handleMessage = function(event){
// if(debug==true){console.log("handleMessage: in \n          sid:" + debugSequence++);}
        var theSender = gapi.hangout.getParticipantById(event.senderId).person.displayName;
        var thisMessage = event.message;
        var arrMessage = thisMessage.split("_");
        var messageType = arrMessage[0];
        var messageDetail = (arrMessage.length>1)? arrMessage[1]: "";

        switch(messageType){
            case "handOn":
                this.drawHandmsg(messageDetail, "inline");
                this.indicateProducers();
                break;
            case "handOff":
                this.drawHandmsg(messageDetail, "none");
                this.indicateProducers();
                break;
            default:
//                console.log("Unhandled handleMessage: " + messageType);
                break;
        }
        this.setSectionsDisplay();
// if(debug==true){console.log("     handleMessage: out \n          sid:" + debugSequence++);}
    };

    ProStudioApp.prototype.refreshEverything = function(event){
// /if(debug==true){console.log("refreshEverything: in \n          sid:" + debugSequence++);}
        //Montor for client changes
        var theKeys = event.addedKeys;
        var theKey, theValue;
        if(window.refMilli==0){
            var newRefMilli = gapi.hangout.data.getValue("RefTime");
            if(newRefMilli==undefined){
                gapi.hangout.data.setValue("RefTime", theKeys[0].timestamp.toString());
            }else{
                window.refMilli = newRefMilli;
            }
        }

        if(window.broadcastMilli==0){
            if((window.isOnAir)&&(gapi.hangout.onair.isBroadcasting())){
                var newBroadcastMilli = gapi.hangout.data.getValue("BRefTime");
                if(newBroadcastMilli==undefined){
                    gapi.hangout.data.setValue("BRefTime", theKeys[0].timestamp.toString());
                }else{
                    window.broadcastMilli = newBroadcastMilli;
                }
            }
        }

        for(var i = 0; i < theKeys.length; i++){
            theKey = event.addedKeys[i].key;
            theValue = event.addedKeys[i].value;
// if(debug==true){console.log("refreshEverything: 1 key: " + theKey + " \n          sid:" + debugSequence++);}
            if(theKey!=undefined){
                switch(theKey){
                    case "MsgMute": case "MsgUnMute": case "CamMute": case "CamUnMute": case "LogoShow": case "LogoHide": case "MsgBanz":
                        this.processAction(theKey, theValue);
                        break;
                    case "LockProducer": 
                         console.log('locking refreshEverything');
                         //console.log(theValue);
                         //console.log(gapi.hangout.getParticipantById(theValue));
                         //.person.displayName;

                         //var id = gapi.hangout.getLocalParticipantId();

                        // Get the default video feed.
                        //var feed = gapi.hangout.layout.getDefaultVideoFeed();

                        // Set the local participant to be sticky.
                        // Note that this will close any main area app.
                        //feed.setDisplayedParticipant(theValue.usrID);

                            //this.showFocus();
                        //gapi.hangout.layout.getDefaultVideoFeed().setDisplayedParticipant(theValue);
                        //console.log("TIENE LA PALABRAA:::::"+window.tieneLaPalabraID);
                        //gapi.hangout.onair.setDisplayedParticipantInBroadcast(window.tieneLaPalabraID);
                        //gapi.hangout.data.setValue("focusParticipantID", window.tieneLaPalabraID);
                        //console.log("THE VALUE::::"+theValue);//window.tieneLaPalabraID
                        
                        //ProStudioApp.prototype.processHostAction("SetFocus", window.tieneLaPalabraID);
                        //gapi.hangout.layout.getDefaultVideoFeed().setDisplayedParticipant(theValue)
                        this.processAction(theKey, theValue);
                        //focusParticipantID  
                        //this.processHostAction("SetFocus", window.tieneLaPalabraID);
                        break;
                    case "UnlockProducer": 
                        console.log('unlocking refreshEverything');
                        gapi.hangout.layout.getDefaultVideoFeed();
                        //this.processAction(theKey, theValue);
                        //gapi.hangout.layout.getDefaultVideoFeed();
                        //console.log(idParticipanteFocoCamara);
                        //gapi.hangout.onair.setDisplayedParticipantInBroadcast(window.tieneLaPalabraID);
                        //gapi.hangout.data.setValue("focusParticipantID", window.tieneLaPalabraID);
                        break;
                    case "OffStage": case "OnStage": case "ToggleStage": case "SetFocus":
                        this.processHostAction(theKey, theValue);
                        break;
                    case "MsgMsg":
                        this.showMessage();
                        break;
		            case "DarLaPalabra":
                        gapi.hangout.layout.getDefaultVideoFeed().setDisplayedParticipant(theValue);
                        break;
                    case "Producers":
                        this.displayParticipants();
                        this.displayPedidos();
                        this.displayPanelSelector();
                        this.displayTools();
                        this.displayTopics();
                        this.displayStatus();
                        break;
                    case "HostID":
                        this.displayParticipants();
                        this.displayPedidos();
                        this.displayPanelSelector();
                        this.displayTools();
                        this.displayTopics();
                        this.displayStatus();
                        break;
                    case "Topics":
                        this.displayTopics();
                        this.displayPanelSelector();
                        this.displayStatus();
                        document.getElementById("txtAddTopic").focus();
                        break;
                    case "Pedidos":
                        this.displayPedidos();
                        break;
                    case "TieneLaPalabraID":
			            window.tieneLaPalabraID = gapi.hangout.data.getValue("TieneLaPalabraID");
                        this.displayParticipants();
                        break;
                    case "CurTopicID":
                        this.displayTopics();
                        this.displayStatus();
                        break;
                    case "IsNewPartInBroadcast":
                        window.isNewPartInBroadcast = (theValue == "true");
                        this.displayStatus();
                        break;
                    case "IsNotificationMuted":
                        window.isNotificationMuted = (theValue == "true");
                        this.displayStatus();
                        break;
                    case "IsFilmstripHidden":
                        window.isFilmstripHidden = theValue;
                        this.displayStatus();
                        break;
                    case "YouTubeLiveID":
                        window.youTubeLiveID = theValue;
                        this.displayStatus();
                        break;
                    case "UpdateStatus":
                        this.displayStatus();
                        break;
                    case "UpdateParticipants":
                        this.displayParticipants();
                        this.displayPedidos();
                        break;
                    case "UpdateTools":
                        this.displayTools();
                        break;
                    case "UpdateTopics":
                        this.displayTopics();
                        this.displayPanelSelector();
                        break;
                    case "RefTime": case "GoogIDs":
                        break;
                    case "focusParticipantID":
                        this.showFocus();
                        break;
                    default:
//                        console.log("Unhandled Key: " + theKey);
                        break;
                }
            }
        }
        this.setSectionsDisplay();
// if(debug==true){console.log("     refreshEverything: out \n          sid:" + debugSequence++);}
    };


//Display Status
    ProStudioApp.prototype.displayStatus = function(){
// if(debug==true){console.log("displayStatus: in \n          sid:" + debugSequence++);}
        var hostID = this.getHostID();
        var isHost = (hostID.indexOf(window.myParticipantID)>=0)
        var producers, isProducer;
        if(isHost){
            isProducer = true;
        }else{
            producers = this.getProducers();
            isProducer = this.isProducer(window.myParticipantID, producers);
        }
        var isPublic = gapi.hangout.isPublic();
        var tblContainer = document.createElement("table");
        tblContainer.setAttribute("id", "tblStatus");
        tblContainer.style.display = window.contentDisplay["statusContent"];

        var tr, statusName, statusValue;

        //Begin Current and Next Topics
        var cTopicID, currentTopic, nextTopic, arrTopics, maxTopicID, topicToolDiv, divTopic, prevID, nextID;
        arrTopics = this.getTopics();
        if(arrTopics.length>0){
            //Write Current Topic
            cTopicID = gapi.hangout.data.getValue("CurTopicID");
            maxTopicID = arrTopics.length - 1;
            if((maxTopicID>cTopicID)){
                nextID = parseInt(cTopicID) + 1;
            }else{
                nextID = null;
            }

            tr = document.createElement("tr");
            tr.className = "rowLine";
            statusName = document.createElement("td");
            statusName.className = "statName";
            statusName.innerHTML = "Current Topic";
            statusName.colSpan = 2;
            statusName.title = "\"Current Topic\" is the agenda item that the Hangout is discussing at this moment.";

            if((isProducer)&&(maxTopicID>=0)){
                topicToolDiv = document.createElement("div");
                topicToolDiv.className = "statusTopicTools";
                statusName.appendChild(topicToolDiv);

                if((cTopicID>0)){
                    prevID = parseInt(cTopicID) - 1;
                    divTopic = document.createElement("div");
                    divTopic.setAttribute("id", "tid" + prevID);
                    divTopic.title = "Click (or press the left arrow key on your keyboard) to back up to the previous topic.";
                    divTopic.innerHTML = "\u25c4";
                    divTopic.className = "statusTopicChange";
                    divTopic.onclick = this.prevTopic;
                    topicToolDiv.appendChild(divTopic);
                }

                if((maxTopicID>cTopicID)){
                    divTopic = document.createElement("div");
                    divTopic.setAttribute("id", "tid" + nextID);
                    divTopic.title = "Click (or press the right arrow key on your keyboard) to advance to the next topic.";
                    divTopic.innerHTML = "\u25ba";
                    divTopic.className = "statusTopicChange";
                    divTopic.onclick = this.nextTopic;
                    topicToolDiv.appendChild(divTopic);
                }
                statusName.appendChild(topicToolDiv);
            }

            tr.appendChild(statusName);
            tblContainer.appendChild(tr);

            tr = document.createElement("tr");
            statusValue = document.createElement("td");
            statusValue.className = "statusCurrentTopicText";
            statusValue.colSpan = 2;
            if(cTopicID != undefined){
                currentTopic = arrTopics[cTopicID];
                if(currentTopic==undefined){
                    currentTopic = "None selected";
                    cTopicID = -1;
                }
            }else{
                currentTopic = "None selected";
                cTopicID = -1;
            }
            if(currentTopic == "None selected"){
                statusValue.title = "No agenda item has been selected.";
            }else{
                statusValue.title = "The current topic of discussion is: " + currentTopic;
            }
            statusValue.innerHTML = currentTopic;
            statusValue.title = currentTopic;
            tr.appendChild(statusValue);
            tblContainer.appendChild(tr);

            //Write Next Topic
            if(nextID!=null){
                tr = document.createElement("tr");
                statusValue = document.createElement("td");
                statusValue.className = "statusNextTopicText";
                statusValue.colSpan = 2;
                nextTopic = arrTopics[nextID];
                statusValue.title = "The next topic of discussion is: " + nextTopic;
                statusValue.innerHTML = "Next: " + nextTopic;
                tr.appendChild(statusValue);
                tblContainer.appendChild(tr);
            }
        }

        //Write On Air Status
        tr = document.createElement("tr");
        statusName = document.createElement("td");
        statusName.className = "statName";

        if(window.isOnAir){
            statusName.innerHTML = "Hangout On Air:";
            statusName.title = "This Hangout On Air may have ten participants, and can be broadcast live in the Google Plus Stream and YouTube with no additional software.";
        }else{
            statusName.innerHTML = "Hangout:";
            statusName.title = "This Hangout is limited to ten participants and only those ten can view the Hangout without an additional streaming service being used.";
        }

        tr.appendChild(statusName);

        statusValue = document.createElement("td");
        statusValue.className = "statValue";

        if(window.isOnAir){
            //Write Broadcast Status
            if(gapi.hangout.onair.isBroadcasting()){
                statusValue.innerHTML = "STREAMING LIVE";
                statusValue.style.color = "red";
                statusValue.title = "This Hangout On Air is currently broadcasting live in the Google Plus Stream and YouTube.";
            }else{
                statusValue.innerHTML = "Not Broadcasting";
                statusValue.title = "This Hangout On Air is not broadcasting: only those in the Hangout can see and hear you.";
            }
        }else{
            //Public Status
            if(isPublic){
                statusValue.innerHTML = "Public Invited";
                statusValue.title = "Anyone with a Google Plus account may join this Hangout.";
            }else{
                statusValue.innerHTML = "Not Public";
                statusValue.title = "Only specific users and circle members may join this Hangout.";
            }
        }
        tr.appendChild(statusValue);
        tblContainer.appendChild(tr);

        if(window.isOnAir){
            if(isHost||isProducer){
                tr = document.createElement("tr");
                statusName = document.createElement("td");
                statusName.className = "statName";
                statusName.innerHTML = "Participants Enter: ";
                statusName.title = "When a new participant first joins the Hangout, they can be either \"On-Stage\" or \"Off-Stage\".\n\nClick the value to the right to toggle between these options.";
                tr.appendChild(statusName);

                statusValue = document.createElement("td");
                statusValue.className = "statValue";
                var newStageState = (window.isNewPartInBroadcast)? "On-Stage": "Off-Stage";
                statusValue.innerHTML = newStageState;
                statusValue.className = "linkTool";
                statusValue.title = "Click to toggle the New Pariticipants starting state between \"On-Stage\" and \"Off-Stage\".";
                statusValue.setAttribute("id", "tdToggleStage");
                statusValue.onclick = this.requestHostAction;
                tr.appendChild(statusValue);
                tblContainer.appendChild(tr);

                //Show or Hide Filmstrip
                tr = document.createElement("tr");
                statusName = document.createElement("td");
                statusName.className = "statName";
                statusName.innerHTML = "Filmstrip is: ";
                statusName.title = "The filmstrip is either hidden or visible in the YouTube stream.\n\nClick the value to the right to cycle between these options:\n    Hidden (Always display main feed only)\n    Displayed (Always display main feed and filmstrip)\n    Auto (Automatically hide filmstrip when there is one user)";
                tr.appendChild(statusName);

                statusValue = document.createElement("td");
                statusValue.className = "statValue";
                var newFilmstripState = window.isFilmstripHidden;
                if(newFilmstripState==1){
                    newFilmstripState = "Hidden";
                }else if(newFilmstripState==2){
                    newFilmstripState = "Displayed";
                }else{
                    newFilmstripState = "Auto";
                }
                statusValue.innerHTML = newFilmstripState;
                statusValue.className = "linkTool";
                statusValue.title = "Click to cycle the Filmstrip between:\n    Hidden (Always display main feed only)\n    Displayed (Always display main feed and filmstrip)\n    Auto (Automatically hide filmstrip when there is one user)";
                statusValue.setAttribute("id", "tdToggleFilmstrip");
                statusValue.onclick = this.requestHostAction;
                tr.appendChild(statusValue);
                tblContainer.appendChild(tr);

                //Mute Notifications
                tr = document.createElement("tr");
                statusName = document.createElement("td");
                statusName.className = "statName";
                statusName.innerHTML = "Notifications are: ";
                statusName.title = "Hangout Notifications are either \"Muted\" or \"Audible\" in the Hangout.\n\nClick the value to the right to toggle between these options.";
                tr.appendChild(statusName);

                statusValue = document.createElement("td");
                statusValue.className = "statValue";
                var newNotificationState = (window.isNotificationMuted)? "Muted": "Audible";
                statusValue.innerHTML = newNotificationState;
                statusValue.className = "linkTool";
                statusValue.title = "Click to toggle Hangout Notifications between \"Muted\" and \"Audible\".";
                statusValue.setAttribute("id", "tdToggleNotifications");
                statusValue.onclick = this.requestHostAction;
                tr.appendChild(statusValue);
                tblContainer.appendChild(tr);
            }
        }

        if(isHost||isProducer){
            //Hangout Link
            tr = document.createElement("tr");
            statusName = document.createElement("td");
            statusName.className = "statName";
            statusName.innerHTML = "Join Link: ";
            statusName.title = "Provide this link to participants to load Pro Studio by default on entering the Hangout.\n\nRight-click this link and select \"Copy link address\", then paste the link into your invitation post.";
            tr.appendChild(statusName);

            statusValue = document.createElement("td");
            statusValue.className = "statValue";
            var hangoutURL = gapi.hangout.getHangoutUrl();
            var theAppID = "893851448980";
            var hangoutLink;
            if(hangoutURL.indexOf(theAppID)>0){
                hangoutLink = hangoutURL;
            }else{
                var theSep = (hangoutURL.indexOf("?")>0)? "&": "?";
                hangoutLink = hangoutURL + theSep + "gid=" + theAppID;
            }
            statusValue.innerHTML = "<a href='" + hangoutLink + "' target='_blank'>Hangout Invitation</a>";
            statusValue.title = "Provide this link to participants to load Pro Studio by default on entering the Hangout.\n\nRight-click this link and select \"Copy link address\", then paste the link into your invitation post.";
            tr.appendChild(statusValue);
            tblContainer.appendChild(tr);
        }

        if(window.isOnAir){
            //YouTube Link
            if(window.youTubeLiveID.length > 0){
                tr = document.createElement("tr");
                statusName = document.createElement("td");
                statusName.className = "statName";
                statusName.innerHTML = "Broadcast Link: ";
                statusName.title = "Provide this link to external viewers to watch the broadcast on YouTube.\n\nAlternatively, you can paste this link into Gerwin Sturm's stand-alone Comment Tracker to monitor YouTube comments.\n\nRight-click this link and select \"Copy link address\", then paste the link into your invitation post or Comment Tracker.";
                tr.appendChild(statusName);

                statusValue = document.createElement("td");
                statusValue.className = "statValue";
                var youTubeLink = "//www.youtube.com/watch?v=" + window.youTubeLiveID;
                statusValue.innerHTML = "<a href='" + youTubeLink + "' target='_blank'>YouTube Video</a>";
                statusValue.title = "Provide this link to external viewers to watch the broadcast on YouTube.\n\nAlternatively, you can paste this link into Gerwin Sturm's stand-alone Comment Tracker to monitor YouTube comments.\n\nRight-click this link and select \"Copy link address\", then paste the link into your invitation post or Comment Tracker.";
                tr.appendChild(statusValue);
                tblContainer.appendChild(tr);
            }
        }

        //Comment Tracker Link
        tr = document.createElement("tr");
        statusName = document.createElement("td");
        statusName.className = "statName";
        statusName.innerHTML = "Comments: ";
        statusName.title = "Keep track of comments by opening Gerwin Stum's Comment Tracker.";
        tr.appendChild(statusName);

        statusValue = document.createElement("td");
        statusValue.className = "linkTool";
        statusValue.innerHTML = "Comment Tracker";
        statusValue.title = "Use this link to open Gerwin Sturm's stand-alone Comment Tracker.\n\nIn the resulting window, paste the Player Post URL, YouTube URL and any related Twitter HashTags to track comments from those locations.";
        statusValue.onclick = this.openCommentTracker;

        tr.appendChild(statusValue);
        tblContainer.appendChild(tr);

        //Get the Status Container and clear it just in case
        var divContainer = document.getElementById("statusContainer");
        divContainer.innerHTML = "";

        var fieldset = document.createElement("fieldset");
        fieldset.setAttribute("id", "fldStatus");
        divContainer.appendChild(fieldset);

        var legend = document.createElement("legend");
        legend.innerHTML = "Status";
        legend.onclick = this.toggleSectionDisplay;
        legend.title = "The Status section displays information about the current state of the Hangout.\n\nYou can hide this by clicking on 'Status'.";
        fieldset.appendChild(legend);
        fieldset.appendChild(tblContainer);

        var br = document.createElement("br");
        br.className = "shortBreak";
        fieldset.parentNode.appendChild(br);
// if(debug==true){console.log("     displayStatus: out \n          sid:" + debugSequence++);}
    };


    
//Display Participants
    ProStudioApp.prototype.displayParticipants = function(){
// if(debug==true){console.log("displayParticipants: in \n          sid:" + debugSequence++);}
        //Get the Participant Container and clear it just in case
        var divContainer = document.getElementById("participantContainer");
        divContainer.innerHTML = "";

        var fieldset = document.createElement("fieldset");
        fieldset.setAttribute("id", "fldParticipants");
        divContainer.appendChild(fieldset);

        var ulContainer = document.createElement("ul");
        ulContainer.setAttribute("id", "ulParticipants");
        ulContainer.style.display = window.contentDisplay["participantContent"];
        var li;

        //Get all participants and loop through each, creating each LI to display them
        var currentClient, thisID, theName, theNameSpan, input, handImg, onImg, thisTitle;
        var clients = gapi.hangout.getParticipants();
        var hostID = ProStudioApp.prototype.getHostID();
        var producers = ProStudioApp.prototype.getProducers();
        var isProducer = ProStudioApp.prototype.isProducer(window.myParticipantID, producers);
        var isHost = (hostID.indexOf(window.myParticipantID)>=0);
        var arrHandledIDs = new Array();
	var pedidosPalabra = this.getPedidos();
        for(var i = 0; i < clients.length; i++){
            if(clients[i].person.displayName.indexOf("Broadcasting Service")<0){
                //Write each participant with indicators of status
                currentClient = clients[i];
                thisID = currentClient.id.split("^")[1];

                if(arrHandledIDs.indexOf(thisID)<0){
                    arrHandledIDs[arrHandledIDs.length] = thisID;
                    li = document.createElement("li");
                    li.setAttribute("id", "li" + thisID);

                    theName = currentClient.person.displayName;
                    if(theName==undefined){
                        theName = "[Unknown]";
                    }

                    if(isProducer||isHost){
                        input = document.createElement("input");
                        input.setAttribute("type", "checkbox");
                        input.setAttribute("id", "chkP" + thisID);
                        input.setAttribute("value", thisID);
                        input.title = "Marcar para seleccionar a " + theName + " como objetivo de una de las herramientas.";
                        if(window.arrSelected.indexOf(thisID)>=0){
                            input.setAttribute("checked", "true");
                        }
                        input.onclick = this.setSelected;
                        li.appendChild(input);
                    }

                    if(window.isOnAir==true){
                        onImg = document.createElement("img");
                        onImg.setAttribute("align", "right");
                        onImg.setAttribute("style", "vertical-align: middle;");
                        onImg.setAttribute("id", "onImg" + thisID);
                        thisTitle = "This image indicates whether this participant is the main focus in the broadcast stream.\n\nBlue outline indicates the broadcast stream.";
                        if(isProducer||isHost){
                            onImg.setAttribute("style", "cursor: pointer; vertical-align: middle;");
                            thisTitle += "\n\nClick to SET BROADCAST FOCUS on this participant.";
                            onImg.onclick = this.setDisplayedParticipant;
                        }
                        onImg.title = thisTitle;
                        onImg.setAttribute("src", "//vspotnow.com/Hangout/prodstud/images/offball.png");
                        li.appendChild(onImg);
                    }

                    theNameSpan = document.createElement("div");
                    theNameSpan.className = "participanteDiv";
                    theNameSpan.innerHTML = theName;
                    li.appendChild(theNameSpan);

                    handImg = document.createElement("img");
                    handImg.setAttribute("style", "vertical-align: middle;");
                    handImg.style.display = (pedidosPalabra.indexOf(currentClient.id)>=0)? "inline": "none"; //ACA
                    handImg.setAttribute("align", "right");
                    handImg.setAttribute("id", "img" + thisID);
                    handImg.title = "Esta imagen indica que el participante tiene una pregunta o un comentario para compartir.";
                    handImg.setAttribute("src", "//directorhangout.googlecode.com/svn/trunk/images/icons/ManoArriba.png");
                    li.appendChild(handImg);
                    ulContainer.appendChild(li);
                }
            }
        }

        li = document.createElement("li");
        if(isProducer||isHost){
            input = document.createElement("input");
            input.setAttribute("type", "checkbox");
            input.setAttribute("id", "allParticipants");
            input.title = "Click para seleccionar automaticamente a todos los participantes.";
            input.onclick = this.setAllSelected;
            li.appendChild(input);
	    
	    seleccionarTodosDiv = document.createElement("div");
	    seleccionarTodosDiv.className = "seleccionarTodosDiv";
	    seleccionarTodosDiv.innerHTML = "Seleccionar todos";
	    li.appendChild(seleccionarTodosDiv);
        }

        //Raise Hand
        var newDiv = document.createElement("div");
        newDiv.setAttribute("style", "display: inline; float: right;");

        input = document.createElement("input");
//        input.setAttribute("type", "image");
        input.setAttribute("id", "btnRaiseHand");
	input.setAttribute("type", "button");
        input.setAttribute("value", "Pedir la palabra");
        input.setAttribute("src", "//directorhangout.googlecode.com/svn/trunk/images/icons/ManoArriba.png");
        input.title = "Pedir la palabra.";
        input.className = "tool";
        input.onclick = this.toggleHand;
        newDiv.appendChild(input);
        li.appendChild(newDiv);
        ulContainer.appendChild(li);

        input = null;

//        if(this.isBeta() && window.showbeta){
            if((window.isOnAir==true) && (isProducer||isHost)){
                var thisBR = document.createElement("br");
                thisBR.className = "shortBreak";
                newDiv.appendChild(thisBR);
                //Auto Focus
                input = document.createElement("input");
                input.setAttribute("type", "button");
                input.setAttribute("id", "AutoFocus");
                input.setAttribute("value", "Auto-Switching");
                input.title = "Click to SET BROADCAST FOCUS to AUTO.";
                input.className = "tool";
                input.onclick = this.setDisplayedParticipant;
                newDiv.appendChild(input);
                input = null;
            }
//        }

        var legend = document.createElement("legend");
        legend.innerHTML = "Participantes";
        legend.title = "La seccion Participantes muestra informacion acerca de los participantes del Hangout.\n\nAl pasar el mouse sobre cada participante se obtiene informacion de los diferentes tipos de usuarios.\n\nSe puede ocultar este panel haciendo click en 'Participantes'.";
        legend.onclick = this.toggleSectionDisplay;
        fieldset.appendChild(legend);
        fieldset.appendChild(ulContainer);

        var br = document.createElement("br");
        br.className = "shortBreak";
        fieldset.parentNode.appendChild(br);

        this.indicateProducers();
        this.showFocus();
 //       this.sendHandMessage();
// if(debug==true){console.log("     displayParticipants: out \n          sid:" + debugSequence++);}
    };

//Display Panel Selection
    ProStudioApp.prototype.displayPanelSelector = function(){
// if(debug==true){console.log("displayPanelSelector: in \n          sid:" + debugSequence++);}
        //Get the Panel Selector Container and clear it just in case
        var divContainer = document.getElementById("panelSelectionContainer");
        divContainer.innerHTML = "";

        var hostID = ProStudioApp.prototype.getHostID();
        var producers = ProStudioApp.prototype.getProducers();

        if((hostID.indexOf(window.myParticipantID)>=0)||(ProStudioApp.prototype.isProducer(window.myParticipantID, producers))){
            var panelDiv = document.createElement("div");
            panelDiv.setAttribute("id", "selPanel");
            divContainer.appendChild(panelDiv);

            var divSelector = document.createElement("div");
            divSelector.setAttribute("id", "divSelTools");
            divSelector.className = window.contentDisplay["divSelTools"];
            divSelector.innerHTML = "Tools";
            divSelector.title = "Click to display the Tools panel";
            divSelector.onclick = this.selectDisplay;
            panelDiv.appendChild(divSelector);

            divSelector = document.createElement("div");
            divSelector.setAttribute("id", "divSelTopics");
            divSelector.className = window.contentDisplay["divSelTopics"];
            divSelector.innerHTML = "Topics";
            divSelector.title = "Click to display the Topics panel";
            divSelector.onclick = this.selectDisplay;
            panelDiv.appendChild(divSelector);

            var br = document.createElement("br");
            br.className = "shortBreak";
            panelDiv.parentNode.appendChild(br);
        }
// if(debug==true){console.log("     displayPanelSelector: out \n          sid:" + debugSequence++);}
    };

//Display Tools
    ProStudioApp.prototype.displayTools = function(){
// if(debug==true){console.log("displayTools: in \n          sid:" + debugSequence++);}
        var divContainer = document.getElementById("toolContainer");
        divContainer.innerHTML = "";
        var producers = ProStudioApp.prototype.getProducers();
        if(ProStudioApp.prototype.isProducer(window.myParticipantID, producers)){
            var fieldset = document.createElement("fieldset");
            fieldset.setAttribute("id", "fldTools");
            var legend = document.createElement("legend");
            legend.innerHTML = "Herramientas";
            legend.title = "Las herramientas aplican a los participantes seleccionados arriba.\n\n";
            legend.onclick = this.toggleSectionDisplay;

            fieldset.appendChild(legend);
            divContainer.appendChild(fieldset);

            var toolsDiv = document.createElement("div");
            toolsDiv.setAttribute("id", "toolsDiv");
            toolsDiv.style.display = window.contentDisplay["toolContent"];
            fieldset.appendChild(toolsDiv);

            var input, spacer;
            
            //Mute Mic
            input = document.createElement("input");
            input.setAttribute("type", "image");
            input.setAttribute("id", "btnMicMute");
            input.setAttribute("src", "//directorhangout.googlecode.com/svn/trunk/images/icons/MuteMic.png");
            input.title = "Click para silenciar a todos los participantes seleccionados, incluyendo a los que no estan utilizando la aplicacion.";
            input.className = "tool";
            input.onclick = this.requestAction;
            toolsDiv.appendChild(input);
            input = null;
            //Un-Mute Mic
            input = document.createElement("input");
            input.setAttribute("type", "image");
            input.setAttribute("id", "btnMicUnMute");
            input.setAttribute("src", "//directorhangout.googlecode.com/svn/trunk/images/icons/UnMuteMic.png");
            input.title = "Click para encender el microfono de los usuarios seleccionados.";
            input.className = "tool";
            input.onclick = this.requestAction;
            toolsDiv.appendChild(input);
            input = null;

            spacer = document.createElement("div");
            spacer.className = "spacer";
            spacer.innerHTML = "&nbsp;&nbsp;";
            toolsDiv.appendChild(spacer);

            //Hide Cam
            input = document.createElement("input");
            input.setAttribute("type", "image");
            input.setAttribute("id", "btnCamMute");
            input.setAttribute("src", "//directorhangout.googlecode.com/svn/trunk/images/icons/MuteCam.png");
            input.title = "Click para apagar el video de los usuarios seleccionados.\n\nNo funciona para usuarios que no esten en la aplicacion.";
            input.className = "tool";
            input.onclick = this.requestAction;
            toolsDiv.appendChild(input);
            input = null;

            //Un-hide Cam
            input = document.createElement("input");
            input.setAttribute("type", "image");
            input.setAttribute("id", "btnCamUnMute");
            input.setAttribute("src", "//directorhangout.googlecode.com/svn/trunk/images/icons/UnMuteCam.png");
            input.title = "Click activar el video de los usuarios seleccionados.\n\nNo funciona para usuarios que no esten en la aplicacion.";
            input.className = "tool";
            input.onclick = this.requestAction;
            toolsDiv.appendChild(input);
            input = null;

            spacer = document.createElement("div");
            spacer.className = "spacer";
            spacer.innerHTML = "&nbsp;&nbsp;";
            toolsDiv.appendChild(spacer);

            //Lock User Video Focus
            input = document.createElement("input");
            input.setAttribute("type", "image");
            input.setAttribute("id", "btnLockVideoFocus");
            input.setAttribute("src", "//directorhangout.googlecode.com/svn/trunk/images/icons/lock.png");
            input.title = "Click para Lockear el video del participante seleccionado.";
            input.className = "tool";
            //input.onclick = this.requestAction;
            input.onclick = this.lockVideo;
            toolsDiv.appendChild(input);
            input = null;

            //Unlock User Video Focus
            input = document.createElement("input");
            input.setAttribute("type", "image");
            input.setAttribute("id", "btnUnlockVideoFocus");
            input.setAttribute("src", "//directorhangout.googlecode.com/svn/trunk/images/icons/unlock.png");
            input.title = "Click para Unlockear el video del participante seleccionado.";
            input.className = "tool";
            //input.onclick = this.requestAction;
            input.onclick = this.unlockVideo;
            toolsDiv.appendChild(input);
            input = null;

            //addspacer
            spacer = document.createElement("div");
            spacer.className = "spacer";
            spacer.innerHTML = "&nbsp;&nbsp;";
            toolsDiv.appendChild(spacer);
            
            if(window.isOnAir==true){
                //Off-Stage
                input = document.createElement("input");
                input.setAttribute("type", "image");
                input.setAttribute("id", "btnOffStage");
                input.setAttribute("src", "//vspotnow.com/Hangout/prodstud/images/icons/OffStage.png");
                input.title = "Click to set selected users Off-Stage, including Non-App Users.";
                input.className = "tool";
                input.onclick = this.requestHostAction;
                toolsDiv.appendChild(input);
                input = null;

                //On-Stage
                input = document.createElement("input");
                input.setAttribute("type", "image");
                input.setAttribute("id", "btnOnStage");
                input.setAttribute("src", "//vspotnow.com/Hangout/prodstud/images/icons/OnStage.png");
                input.title = "Click to set selected users On-Stage, including Non-App Users.";
                input.className = "tool";
                input.onclick = this.requestHostAction;
                toolsDiv.appendChild(input);pedidoContainer
                input = null;

                spacer = document.createElement("div");
                spacer.className = "spacer";
                spacer.innerHTML = "&nbsp;&nbsp;";
                toolsDiv.appendChild(spacer);
            }

            //Set Producers
            
            input = document.createElement("input");
            input.setAttribute("type", "image");
            input.setAttribute("id", "btnRevokeProducer");
            input.setAttribute("src", "//vspotnow.com/Hangout/prodstud/images/icons/RevokeProducer.png");
            input.title = "Click to revoke Producer rights from all selected users.";
            input.className = "tool";
            input.onclick = this.setProducers;
            toolsDiv.appendChild(input);
            input = null;

            //Revoke Producers
            input = document.createElement("input");
            input.setAttribute("type", "image");
            input.setAttribute("id", "btnSetProducer");
            input.setAttribute("src", "//vspotnow.com/Hangout/prodstud/images/icons/SetProducer.png");
            input.title = "Click to designate all selected users as Hangout Producers.\n\nThis cannot be used on Non-App Users.";
            input.className = "tool";
            input.onclick = this.setProducers;
            toolsDiv.appendChild(input);
            input = null;
	    
            spacer = document.createElement("div");
            spacer.className = "spacer";
            spacer.innerHTML = "&nbsp;&nbsp;";
            toolsDiv.appendChild(spacer);

            //Set Banish
            input = document.createElement("input");
            input.setAttribute("type", "image");
            input.setAttribute("id", "btnSetBanish");
            input.setAttribute("src", "//directorhangout.googlecode.com/svn/trunk/images/icons/Banish.png");
            input.title = "Click para quitar de la videollamada a todos los usuarios seleccionados. Deberian ser bloqueados primero para que no puedan volver a unirse..\n\n Esto no puede utilizarse en usuarios que no utilicen hangouts moderadas.";
            input.className = "tool bigRed";
            input.onclick = this.requestAction;
            toolsDiv.appendChild(input);
            input = null;

            br = document.createElement("br");
            toolsDiv.appendChild(br);

            /*//Stand By
            input = document.createElement("input");
            input.setAttribute("type", "button");
            input.setAttribute("id", "btnStandBy");
            input.setAttribute("value", "Standby");
            input.title = "Click (or press \"s\" in your keyboard) to signal all selected users to Stand By.\n\nThis cannot be used on Non-App Users.";
            input.className = "tool";
            input.onclick = this.requestCue;
            toolsDiv.appendChild(input);
            input = null;

            //All Clear
            input = document.createElement("input");
            input.setAttribute("type", "button");
            input.setAttribute("id", "btnClear");
            input.setAttribute("value", "Clear");
            input.title = "Click (or press \"c\" in your keyboard) to signal all selected users that they are clear... the segment is over and they are off-camera.\n\nThis cannot be used on Non-App Users.";
            input.className = "tool";
            input.onclick = this.requestCue;
            toolsDiv.appendChild(input);
            input = null;

            //Wrap Up
            input = document.createElement("input");
            input.setAttribute("type", "button");
            input.setAttribute("id", "btnWrapUp");
            input.setAttribute("value", "Wrap Up");
            input.title = "Click (or press \"w\" in your keyboard) to signal all selected users to Wrap up.\n\nThis cannot be used on Non-App Users.";
            input.className = "tool";
            input.onclick = this.requestCue;
            toolsDiv.appendChild(input);
            input = null;
*/
/*
            if(this.isBeta() && window.showbeta){
                //Show Logo
                input = document.createElement("input");
                input.setAttribute("type", "button");
                input.setAttribute("id", "btnLogoShow");
                input.setAttribute("value", "Logo");
                input.title = "ONLY BETA TEST ACCOUNTS SHOULD SEE THIS\n\nClick to display Pro Studio Logo.\n\nThis cannot be used on Non-App Users.";
                input.className = "tool";
                input.onclick = this.requestAction;
                toolsDiv.appendChild(input);
                input = null;

                //Hide Logo
                input = document.createElement("input");
                input.setAttribute("type", "button");
                input.setAttribute("id", "btnLogoHide");
                input.setAttribute("value", "No Logo");
                input.title = "ONLY BETA TEST ACCOUNTS SHOULD SEE THIS\n\nClick to hide Pro Studio Logo.\n\nThis cannot be used on Non-App Users.";
                input.className = "tool";
                input.onclick = this.requestAction;
                toolsDiv.appendChild(input);
                input = null;
            }
*/
            spacer = document.createElement("div");
            spacer.className = "spacer";
            spacer.innerHTML = "&nbsp;<br /><br />";
            toolsDiv.appendChild(spacer);

//    var requestDiv = document.createElement("div");
//    requestDiv.setAttribute("id", "requestDiv");
//    requestDiv.innerHTML = "Who can help to iconify the rest?<br>Contact me :). Thank you.<br />";
//    toolsDiv.appendChild(requestDiv);

            var messageTitle = document.createElement("div");
            messageTitle.innerHTML = "<b>Mensaje</b>";
            messageTitle.title = "The Message tool allows you to enter and send a message or script to the selected users.\n\nEnter your text and click \"Send\" to make the text appear at the top center of their displays.\n\nThis cannot be used on Non-App Users.";
            messageTitle.setAttribute("style", "text-align: left;");

            input = document.createElement("input");
            input.setAttribute("type", "button");
            input.setAttribute("id", "btnSendScript");
            input.setAttribute("value", "Enviar");
            input.setAttribute("style", "float: right;");
            input.title = "Click para enviar un mensaje a los usuarios seleccionados.\n\nEsto no puede utilizarce en usuarios que no utilicen la aplicacion.";
            input.className = "tool";
            input.onclick = this.sendScript;
            messageTitle.appendChild(input);
            toolsDiv.appendChild(messageTitle);

            var txtScript = document.createElement("textarea");
            txtScript.setAttribute("id", "txtScript");
            txtScript.setAttribute("placeholder", "Ingresar el texto a enviar a los participantes seleccionados.");
            txtScript.setAttribute("style", "width: 100%; height: 45px; resize: none;");
            toolsDiv.appendChild(txtScript);

/*
            //TextArea label for pasing scripts to participants
            var innerFieldset = document.createElement("fieldset");
            innerFieldset.className = "scriptLegend";
            innerFieldset.setAttribute("id", "fldScript");
            var innerLegend = document.createElement("legend");
            innerLegend.className = "scriptLegend";
            innerLegend.innerHTML = "Message";
            innerLegend.onclick = this.toggleSectionDisplay;
            innerLegend.title = "The Message tool allows you to enter and send a message or script to the selected users.\n\nEnter your text and click \"Send\" to make the text appear at the top center of their displays.\n\nYou can hide this by clicking on 'Script'.";
            innerFieldset.appendChild(innerLegend);

            var txtScript = document.createElement("textarea");
            txtScript.setAttribute("id", "txtScript");
            txtScript.setAttribute("placeholder", "Enter text to send to selected participants.");
            txtScript.setAttribute("style", "width: 100%; height: 45px; resize: none;");
            innerFieldset.appendChild(txtScript);

            var br = document.createElement("br");
            br.setAttribute("clear", "all");
            innerFieldset.appendChild(br);

            //Send - Click
            input = document.createElement("input");
            input.setAttribute("type", "button");
            input.setAttribute("id", "btnSendScript");
            input.setAttribute("value", "Send");
            input.setAttribute("style", "float: right;");
            input.title = "Click to send all selected users the provided script";
            input.className = "tool";

            input.onclick = this.sendScript;
            innerFieldset.appendChild(input);

            toolsDiv.appendChild(innerFieldset);
*/


        }
        document.getElementById("toolContainer").style.display = window.contentDisplay["toolContainer"];
// if(debug==true){console.log("     displayTools: out \n          sid:" + debugSequence++);}
    };
 //LOCK VIDEO
    ProStudioApp.prototype.lockVideo = function(){
        console.log("LOCK VIDEO FUNCTION");
            var lockUserID;
            var lockName = null;
            var chkBoxes = document.getElementsByTagName("input");
            var myLock = new Array();
            var thisValue = null;
            console.log(chkBoxes);
            for(var i = 0; i < chkBoxes.length; i++){
                if((chkBoxes[i].id.substr(0,4)=="chkP")&&(chkBoxes[i].checked == true)){
                    thisValue = chkBoxes[i].value;
                    console.log(thisValue);

                        /*if(arrTheseIDs.indexOf(thisValue)<0){
                        arrTheseIDs[arrTheseIDs.length] = thisValue;
                    }*/
                }
            }
            if(thisValue != null){
                console.log("array ok");
                myLock[0] = thisValue;     
                lockName = thisValue;
                thisValue = null;
                var partVideo = gapi.hangout.getEnabledParticipants(); 
            // prename.person.displayName;
            //console.log(lockName[0]);
            //console.log(partVideo);
            //console.log(gapi.hangout.getParticipantById(lockName[0]));
            for(i = 0; i < partVideo.length; i++){
                var findlockUserID = partVideo[i].id;
                if(findlockUserID.indexOf(lockName)>0){
                    console.log(findlockUserID.indexOf(lockName));
                    console.log(partVideo[i]);
                    lockUserID = partVideo[i];
                    gapi.hangout.layout.getDefaultVideoFeed().setDisplayedParticipant(lockUserID.id);
                    //ProStudioApp.prototype.processHostAction('SetFocus',myLock);
                    //gapi.hangout.onair.setDisplayedParticipantInBroadcast(lockUserID.id);
                    //gapi.hangout.data.setValue("focusParticipantID", lockUserID.id);
                }else{
                    lockUserID = null;
                }

            }   
            //console.log(lockUserID.id);
            //var userlocked = lockUserID
            //gapi.hangout.layout.getDefaultVideoFeed().setDisplayedParticipant(lockUserID.id);                     
            //cambiar el foco del video y lo dejamos locked a partir de aqui
            }else{
                console.log('Not user checked');
            }

       /* }else{
            arrTheseIDs[arrTheseIDs.length] = "none";
            alert('demasiados selecteds');
        }
        */

    }
 //UNLOCK VIDEO
    ProStudioApp.prototype.unlockVideo = function(){
        console.log("UNLOCK VIDEO FUNCTION");
        //gapi.hangout.onair.clearDisplayedParticipantInBroadcast()
        gapi.hangout.layout.getDefaultVideoFeed().clearDisplayedParticipant();
    }

//Mostrar pedidos de palabra
    ProStudioApp.prototype.displayPedidos = function(){
        //Get the Pedidos Container and clear it just in case
        var divContainer = document.getElementById("pedidosContainer");
        divContainer.innerHTML = "";

        var producers = ProStudioApp.prototype.getProducers();

	// Solo se muestran los pedidos de palabra si se es host o productor
        if((ProStudioApp.prototype.isHost(window.myParticipantID))||(ProStudioApp.prototype.isProducer(window.myParticipantID, producers))){
            var fieldset = document.createElement("fieldset");
            fieldset.setAttribute("id", "fldPedidos");
            divContainer.appendChild(fieldset);

            var legend = document.createElement("legend");
            legend.innerHTML = "Solicitudes";
            legend.title = "Esta lista permite administrar las solicitudes de palabra.";
            legend.onclick = this.toggleSectionDisplay;
            fieldset.appendChild(legend);

            var pedidosTable = document.createElement("table");
            pedidosTable.setAttribute("id", "pedidosTable");
            pedidosTable.style.display = window.contentDisplay["pedidosContent"];
            fieldset.appendChild(pedidosTable);

            //Get all pedidos and loop through each, creating each LI to display them
            var tr, td, maxID, pedidoText, span, pedidos, hasTool;
            pedidos = this.getPedidos();
            maxID = pedidos.length - 1;
            var tieneLaPalabraID = gapi.hangout.data.getValue("TieneLaPalabraID");
            var thisClass;

            for(var i = 0; i < pedidos.length; i++){
                pedidoText = pedidos[i];
                if(pedidoText.length>0){
                    //Begin THIS pedido
                    tr = document.createElement("tr");
                    tr.setAttribute("id", "pedido" + i);
 
                    //Add Topic Title
                    td = document.createElement("td");
                    td.setAttribute("id", "pid" + i);
		    var nombreParticipante = "Desconocido";
		    if (gapi.hangout.getParticipantById(pedidoText) != null) {
		      nombreParticipante = gapi.hangout.getParticipantById(pedidoText).person.displayName;
		    }

                    td.title = "Click para dar la palabra a: " + nombreParticipante;
		    
                    td.innerHTML = nombreParticipante;
                    td.onclick = this.darLaPalabra;
                    if(tieneLaPalabraID!=undefined){
                        thisClass = (tieneLaPalabraID==i)? "topicSel": "topicText";
                    }else{
                        thisClass = "topicText";
                    }
                    td.className = thisClass;

                    tr.appendChild(td);

		    //Dar la palabra a participante
                    td = document.createElement("td");
                    td.setAttribute("id", "did" + i);
                    td.title =  "Click para dar la palabra a: " + nombreParticipante;
                    td.innerHTML = "<img src='//directorhangout.googlecode.com/svn/trunk/images/icons/darLaPalabra.png'>"; 
                    td.onclick = this.darLaPalabra;
                    td.className = "topicRemove";
                    tr.appendChild(td);

                    //Bajar la mano a participante
                    td = document.createElement("td");
                    td.setAttribute("id", "rp" + i);
                    td.title = "Cancelar pedido de palabra";
                    td.innerHTML = "<img src='//directorhangout.googlecode.com/svn/trunk/images/icons/cancelarVoz.png'>"; 
                    td.onclick = this.removePedidoOtro;
                    td.className = "topicRemove";
                    tr.appendChild(td);
		    
                    pedidosTable.appendChild(tr);
                }
            }

            var br = document.createElement("br");
            br.setAttribute("clear", "all");
            fieldset.parentNode.appendChild(br);

        }
        document.getElementById("pedidosContainer").style.display = window.contentDisplay["pedidosContainer"];
// if(debug==true){console.log("     displayTopics: out \n          sid:" + debugSequence++);}
    };


//Display Topics
    ProStudioApp.prototype.displayTopics = function(){
// if(debug==true){console.log("displayTopics: in \n          sid:" + debugSequence++);}
        //Get the Topics Container and clear it just in case
        var divContainer = document.getElementById("topicContainer");
        divContainer.innerHTML = "";

        var producers = ProStudioApp.prototype.getProducers();

        if((ProStudioApp.prototype.isHost(window.myParticipantID))||(ProStudioApp.prototype.isProducer(window.myParticipantID, producers))){
            var fieldset = document.createElement("fieldset");
            fieldset.setAttribute("id", "fldTopics");
            divContainer.appendChild(fieldset);

            var legend = document.createElement("legend");
            legend.innerHTML = "Topics";
            legend.title = "The Topics tool allows you to enter the show topics so your participants will have a visual cue of what you are talking about, and what's coming next.\n\nEnter a short topic and click \"Add\" to build your list.\n\nThe \"Current Topic\" may be set using the arrows in the Status section or by clicking the topic below.\n\nYou can change the order of topics by using the up and down arrows next to each topic, below.\n\nYou can hide this by clicking on 'Topics'.";
            legend.onclick = this.toggleSectionDisplay;
            fieldset.appendChild(legend);

            var topicsTable = document.createElement("table");
            topicsTable.setAttribute("id", "topicsTable");
            topicsTable.style.display = window.contentDisplay["topicContent"];
            fieldset.appendChild(topicsTable);

            //Get all topics and loop through each, creating each LI to display them
            var tr, td, maxID, topicText, span, topics, hasTool;
            topics = this.getTopics();
            maxID = topics.length - 1;
            var currentTopicID = gapi.hangout.data.getValue("CurTopicID");
            var thisClass;

            for(var i = 0; i < topics.length; i++){
                topicText = topics[i];
                if(topicText.length>0){
                    //Begin THIS Topic
                    tr = document.createElement("tr");
                    tr.setAttribute("id", "topic" + i);

                    td = document.createElement("td");
                    td.className= "moveTd";

                    hasTool = false;

                    //Add Move UP Tool
                    if((i>0)&&(i<=maxID)){
                        span = document.createElement("span");
                        span.setAttribute("id", "up" + i);
                        span.title = "Move this topic up";
                        span.innerHTML = "\u25B2";
                        span.onclick = this.moveTopic;
                        span.className = "topicTool";
                        td.appendChild(span);
                        hasTool = true;
                    }

                    //Add Move DOWN Tool
                    if((i>=0)&&(i<maxID)){
                        span = document.createElement("span");
                        span.setAttribute("id", "dn" + i);
                        span.title = "Move this topic down";
                        span.innerHTML = "\u25BC";
                        span.onclick = this.moveTopic;
                        span.className = "topicTool";
                        td.appendChild(span);
                        hasTool = true;
                    }

                    if(hasTool==false){
                        td.innerHTML = "&nbsp;";
                    }

                    tr.appendChild(td);

                    //Add Topic Title
                    td = document.createElement("td");
                    td.setAttribute("id", "tid" + i);
                    td.title = "Click to set the \"Current Topic\" to: " + topicText;
                    td.innerHTML = topicText;
                    td.onclick = this.setTopic;
                    if(currentTopicID!=undefined){
                        thisClass = (currentTopicID==i)? "topicSel": "topicText";
                    }else{
                        thisClass = "topicText";
                    }
                    td.className = thisClass;

                    tr.appendChild(td);

                    //Add REMOVE Tool
                    td = document.createElement("td");
                    td.setAttribute("id", "rm" + i);
                    td.title = "Remove this topic";
                    td.innerHTML = "<img src='//vspotnow.com/Hangout/prodstud/images/del.png'>";
                    td.onclick = this.moveTopic;
                    td.className = "topicRemove";
                    tr.appendChild(td);
                    topicsTable.appendChild(tr);
                }
            }

            var br = document.createElement("br");
            br.setAttribute("clear", "all");
            fieldset.parentNode.appendChild(br);

            div = document.createElement("div");
            div.setAttribute("id", "addTopic");

            var input = document.createElement("input");
            input.setAttribute("id", "txtAddTopic");
            input.setAttribute("placeholder", "Enter a new Topic and click \"Add\"");
            input.setAttribute("type", "text");
            input.setAttribute("style", "width: 80%;");
            input.onkeydown = this.topicFieldOnKeyDown;
            div.appendChild(input);

            input = document.createElement("input");
            input.setAttribute("id", "btnAddTopic");
            input.setAttribute("value", "Add");
            input.title = "Click to add the text you've entered as a new topic.";
            input.setAttribute("type", "button");
            input.setAttribute("style", "float: right;");
            input.onclick = this.addTopic
            div.appendChild(input);

           // topicsTable.appendChild(div);
            fieldset.appendChild(div);
        }
        document.getElementById("topicContainer").style.display = window.contentDisplay["topicContainer"];
// if(debug==true){console.log("     displayTopics: out \n          sid:" + debugSequence++);}
    };


    
    ProStudioApp.prototype.topicFieldOnKeyDown = function(){
// if(debug==true){console.log("topicFieldKeyUp: in \n          sid:" + debugSequence++);}
        event = (event)? event: window.event;
        var e = event.keyCode;
        if(e==13){
            ProStudioApp.prototype.addTopic();
// if(debug==true){console.log("topicFieldKeyUp: out \n          sid:" + debugSequence++);}
            return false;
        }else{
// if(debug==true){console.log("topicFieldKeyUp: out \n          sid:" + debugSequence++);}
            return true;
        }
    };

    ProStudioApp.prototype.setSelected = function(){
// if(debug==true){console.log("setSelected: in \n          sid:" + debugSequence++);}
        var chkBoxes = document.getElementsByTagName("input");
        var arrTheseIDs = new Array();
        var thisValue;
        for(var i = 0; i < chkBoxes.length; i++){
            if((chkBoxes[i].id.substr(0,4)=="chkP")&&(chkBoxes[i].checked == true)){
                thisValue = chkBoxes[i].value;
                    if(arrTheseIDs.indexOf(thisValue)<0){
                    arrTheseIDs[arrTheseIDs.length] = thisValue;
                }
            }
        }
        if(arrTheseIDs.length<0){
            arrTheseIDs[arrTheseIDs.length] = "none";
        }
        window.arrSelected = arrTheseIDs;
// if(debug==true){console.log("     setSelected: out window.arrSelected.join(':')" + window.arrSelected.join(':') + "\n          sid:" + debugSequence++);}
    };

    ProStudioApp.prototype.setAllSelected = function(){
// if(debug==true){console.log("setAllSelected: in \n          sid:" + debugSequence++);}
        var checkedValue = this.checked;
        var chkBoxes = document.getElementsByTagName("input");
        var arrTheseIDs = new Array();
        for(var i = 0; i < chkBoxes.length; i++){
            if(chkBoxes[i].id.substr(0,4)=="chkP"){
                chkBoxes[i].checked = checkedValue;
                if((arrTheseIDs.indexOf(chkBoxes[i].value)<0)&&(chkBoxes[i].checked==true)){
                    arrTheseIDs[arrTheseIDs.length] = chkBoxes[i].value;
                }
            }
        }
        if(arrTheseIDs.length<0){
            arrTheseIDs[arrTheseIDs.length] = "none";
        }
        window.arrSelected = arrTheseIDs;
// if(debug==true){console.log("     setAllSelected: out \n          sid:" + debugSequence++);}
    };

    ProStudioApp.prototype.selectDisplay = function(){
// if(debug==true){console.log("selectDisplay: in \n          sid:" + debugSequence++);}
        var selectedID = this.id;
        var matched = false;
        var selSwitch, unSelSwitch, showSection, hideSection;
        switch(selectedID){
            case "divSelTools":
                matched = true;
                selSwitch = "divSelTools";
                unSelSwitch = "divSelTopics";
                showSection = "toolContainer";
                hideSection = "topicContainer";
                break;
            case "divSelTopics":
                matched = true;
                selSwitch = "divSelTopics";
                unSelSwitch = "divSelTools";
                showSection = "topicContainer";
                hideSection = "toolContainer";
                break;
        }
        if(matched){
            document.getElementById(selSwitch).className = "selectedPanel";
            window.contentDisplay[selSwitch] = "selectedPanel";
            document.getElementById(unSelSwitch).className = "unSelectedPanel";
            window.contentDisplay[unSelSwitch] = "unSelectedPanel";
            document.getElementById(showSection).style.display = "inline";
            window.contentDisplay[showSection] = "inline";
            document.getElementById(hideSection).style.display = "none";
            window.contentDisplay[hideSection] = "none";
        }
// if(debug==true){console.log("     selectDisplay: out \n          sid:" + debugSequence++);}
    };

    ProStudioApp.prototype.toggleSectionDisplay = function(){
// if(debug==true){console.log("toggleSectionDisplay: in \n          sid:" + debugSequence++);}
        var theParent = this.parentNode;
        var theParentID = theParent.id;
        var oldStyle = window.sectionDisplay[theParentID];
        var newStyle = (oldStyle=="inline")? "none": "inline";
        window.sectionDisplay[theParentID] = newStyle;
        var allChildNodes = theParent.childNodes;
        for(var i = 0; i < allChildNodes.length; i++){
            if(allChildNodes[i].tagName.toLowerCase()!="legend"){
                allChildNodes[i].style.display = newStyle;
            }
        }
// if(debug==true){console.log("     toggleSectionDisplay: out \n          sid:" + debugSequence++);}
    };

    ProStudioApp.prototype.setSectionsDisplay = function(){
// if(debug==true){console.log("setSectionsDisplay: in \n          sid:" + debugSequence++);}
        var theParent, theParentID, theStyle, allChildNodes;
        for(var i = 0; i < window.sectionDisplay.length; i++){
            theParentID = window.sectionDisplay[i].key;
            theStyle = window.sectionDisplay[theParentID];
            theParent = document.getElementById(theParentID);
            allChildNodes = theParent.childNodes;
            for(var j = 0; j < allChildNodes.length; j++){
                if(allChildNodes[j].tagName.toLowerCase()!="legend"){
                    allChildNodes[j].style.display = theStyle;
                }
            }
        }
// if(debug==true){console.log("     setSectionsDisplay: out \n          sid:" + debugSequence++);}
    };

    ProStudioApp.prototype.setDisplayedParticipant = function(){
// if(debug==true){console.log("setDisplayedParticipant: in \n          sid:" + debugSequence++);}
        var inID = this.id;
        var theCommand = "SetFocus";
        var useThisID = inID.replace("onImg", "");
        if(gapi.hangout.getLocalParticipant().isBroadcaster==true){
            ProStudioApp.prototype.processHostAction(theCommand, useThisID);
        }else{
            var d = new Date();
            var theTime = d.getTime();
            var msgID = theCommand + window.myParticipantID.substr(-5) + ":" + theTime.toString().substr(-7);
            var thisMuteReq = {"msgID" : msgID, "usrID": useThisID};
            var tstThisMsg = JSON.stringify(thisMuteReq);
            gapi.hangout.data.setValue(theCommand, tstThisMsg);
        }
// if(debug==true){console.log("     setDisplayedParticipant: out \n          sid:" + debugSequence++);}
    }

    ProStudioApp.prototype.requestHostAction = function(){
 if(debug==true){console.log("requestHostAction: in \n          sid:" + debugSequence++);}
        var inID = this.id;
        var doHost = window.affectHost;
        var theCommand = "";
        switch(inID){
            case "btnOffStage":
                theCommand = "OffStage";
                break;
            case "btnOnStage":
                theCommand = "OnStage";
                break;
            case "tdToggleStage":
                theCommand = "ToggleStage";
                break;
            case "tdToggleFilmstrip":
                theCommand = "ToggleFilmstrip";
                break;
            case "tdToggleNotifications":
                theCommand = "ToggleNotifications";
                break;
            default:
                console.log("Unhandled requestHostAction: " + inID)
            //    doContinue = false;
                break;
        }

        var arrUserIDs = window.arrSelected;
        if(!doHost){
            var hostID = ProStudioApp.prototype.getHostID();
            if(arrUserIDs.indexOf(hostID)>=0){
                arrUserIDs.splice = arrUserIDs.indexOf(hostID);
            }
        }
        var useThisID = ":" + arrUserIDs.join(":") + ":";

        if(gapi.hangout.getLocalParticipant().isBroadcaster==true){
            ProStudioApp.prototype.processHostAction(theCommand, useThisID);
        }else{
            var d = new Date();
            var theTime = d.getTime();
            var msgID = theCommand + window.myParticipantID.substr(-5) + ":" + theTime.toString().substr(-7);
            var thisMuteReq = {"msgID" : msgID, "usrID": useThisID};
            var tstThisMsg = JSON.stringify(thisMuteReq);
            gapi.hangout.data.setValue(theCommand, tstThisMsg);
        }
if(debug==true){console.log("     requestHostAction: out \n          sid:" + debugSequence++);}
    };

    ProStudioApp.prototype.processHostAction = function(inCmd, inIDs){
// if(debug==true){console.log("processHostAction: in \n          sid:" + debugSequence++);}
        if(gapi.hangout.getLocalParticipant().isBroadcaster==true){
            var doOn, theCommand;
            switch(inCmd){
                case "OffStage":
                    theCommand = "InBroadcast";
                    doOn = false;
                    break;
                case "OnStage":
                    theCommand = "InBroadcast";
                    doOn = true;
                    break;
                case "ToggleStage":
                    theCommand = "ToggleStage";
                    doOn = (!gapi.hangout.onair.isNewParticipantInBroadcast());
                    break;
                case "ToggleFilmstrip":
                    theCommand = "ToggleFilmstrip";
                    var curFilStrip = gapi.hangout.onair.getBroadcastDisplayMode();
                    if(curFilStrip==1){
                        doOn = 2;
                    }else if(curFilStrip==2){
                        doOn = 3;
                    }else{
                        doOn = 1;
                    }
                    break;
                case "ToggleStage":
                    theCommand = "ToggleStage";
                    doOn = (!gapi.hangout.onair.isNewParticipantInBroadcast());
                    break;
                case "ToggleNotifications":
                    theCommand = "ToggleNotifications";
                    doOn = (!gapi.hangout.onair.areAudioNotificationsDefaultMuted());
                    break;
                case "MsgMute":
                    theCommand = "Mute";
                    doOn = false;
                    break;
                case "SetFocus":
                    theCommand = "SetFocus";
                    doOn = true;
                    break;
                default:
//                    console.log("Unhandled processHostAction inCmd: " + inCmd);
                    break;
            }
            var participants, thisID, thisParticipantID;
            var d = new Date();
            var theTime = d.getTime().toString();

            switch(theCommand){
                case "InBroadcast":
                    participants = gapi.hangout.getParticipants();
                    for(var i = 0; i < participants.length; i++){
                        thisID = participants[i].id.split("^")[1];
                        if(inIDs.indexOf(thisID)>=0){
                            thisParticipantID = participants[i].id;
                            gapi.hangout.onair.setParticipantInBroadcast(thisParticipantID, doOn);
                            gapi.hangout.data.setValue("focusParticipant", thisID);
                        }
                    }
                    break;
                case "ToggleFilmstrip":
                    gapi.hangout.onair.setBroadcastDisplayMode(doOn);
                    gapi.hangout.data.setValue("isFilmstripHidden", doOn.toString());
                    window.isFilmstripHidden = doOn;
                    gapi.hangout.data.setValue("UpdateStatus", theTime);
                    break;
                case "ToggleNotifications":
                    gapi.hangout.onair.setAudioNotificationsDefaultMute(doOn);
                    gapi.hangout.data.setValue("isNotificationMuted", doOn.toString());
                    window.isNotificationMuted = doOn;
                    gapi.hangout.data.setValue("UpdateStatus", theTime);
                    break;
                case "ToggleStage":
                    gapi.hangout.onair.setNewParticipantInBroadcast(doOn);
                    gapi.hangout.data.setValue("IsNewPartInBroadcast", doOn.toString());
                    window.isNewPartInBroadcast = doOn;
                    gapi.hangout.data.setValue("UpdateStatus", theTime);
                    break;
                case "Mute":
                    participants = gapi.hangout.getParticipants();
                    for(var m = 0; m < participants.length; m++){
                        thisID = participants[m].id.split("^")[1];
                        if((inIDs.indexOf(thisID)>=0)&&(!participants[m].hasAppEnabled)){
                            thisParticipantID = participants[m].id;
                            gapi.hangout.av.muteParticipantMicrophone(thisParticipantID);
                        }
                    }
                    break;
                case "SetFocus":
                    if(inIDs.indexOf("AutoFocus")>=0){
                        gapi.hangout.onair.clearDisplayedParticipantInBroadcast();
                        gapi.hangout.data.setValue("focusParticipantID", "AutoFocus");
                    }else{
                        participants = gapi.hangout.getParticipants();
                        for(var j = 0; j < participants.length; j++){
                            thisParticipantID = participants[j].id;
                            thisID = thisParticipantID.split("^")[1];
                            if(inIDs.indexOf(thisID)>=0){
                                gapi.hangout.onair.setDisplayedParticipantInBroadcast(thisParticipantID);
                                gapi.hangout.data.setValue("focusParticipantID", thisID);
                            }
                        }
                    }
                    this.showFocus();
                    break;
                default:
//                    console.log("Unhandled processHostAction theCommand: " + theCommand);
                    break;
            }
        }
// if(debug==true){console.log("     processHostAction: out \n          sid:" + debugSequence++);}
    };

    ProStudioApp.prototype.requestAction = function(){
// if(debug==true){console.log("requestAction: in \n          sid:" + debugSequence++);}
        var inID = this.id;
        var doHost = window.affectHost;
        var theCommand = "";
        var doContinue = true;
        var theProducers = "";
        switch(inID){
            case "btnLockVideoFocus":
                theCommand = "LockProducer";
                //console.log(inID);
                break;
            case "btnUnlockVideoFocus":
                theCommand = "UnlockProducer";
                //console.log(inID);
                break;
            case "btnMicMute":
                theCommand = "MsgMute";
                break;
            case "btnMicUnMute":
                theCommand = "MsgUnMute";
                break;
            case "btnCamMute":
                theCommand = "CamMute";
                break;
            case "btnCamUnMute":
                theCommand = "CamUnMute";
                break;
            case "btnLogoShow":
                theCommand = "LogoShow";
                break;
            case "btnLogoHide":
                theCommand = "LogoHide";
                break;
            case "btnSetBanish":
                theCommand = "MsgBanz";
                doHost = false;
                break;
            default:
//                console.log("Unhandled requestAction: " + inID);
                doContinue = false;
                break;
        }
        if(doContinue==true){
            var d = new Date();
            var theTime = d.getTime();
            var msgID = theCommand + window.myParticipantID.substr(-5) + ":" + theTime.toString().substr(-7);
            var arrUserIDs = window.arrSelected;
            if(!doHost){
                var hostID = ProStudioApp.prototype.getHostID();
                if(arrUserIDs.indexOf(hostID)>=0){
                    arrUserIDs.splice = arrUserIDs.indexOf(hostID);
                }
            }
            var useThisID = ":" + arrUserIDs.join(":") + ":";
            var thisMuteReq = {"msgID" : msgID, "usrID": useThisID};
            var tstThisMsg = JSON.stringify(thisMuteReq);
            gapi.hangout.data.setValue(theCommand, tstThisMsg);
        }
        return false;
// if(debug==true){console.log("     requestAction: out \n          sid:" + debugSequence++);}
    };

    ProStudioApp.prototype.processAction = function(inCmd, inVal){
// if(debug==true){console.log("processAction: in \n          sid:" + debugSequence++);}
        if((window.affectHost)||(!ProStudioApp.prototype.isHost(window.myParticipantID))){
            if(inVal != undefined){
                var objMessage = JSON.parse(inVal);
                if(objMessage["msgID"]){
                    if((window.arrMessages.indexOf(objMessage["msgID"])<0)&&((objMessage["usrID"]=="all")||(objMessage["usrID"].indexOf(window.myParticipantID)>=0))){
                        //console.log(inCmd);
                        switch(inCmd){
                            case "UnlockProducer":
                                console.log('Desbloqueo producer process action');
                                //this.showFocus();
                                //gapi.hangout.layout.getDefaultVideoFeed();
                                //ProStudioApp.prototype.processHostAction(theCommand, useThisID);
                                break;
                            case "LockProducer":
                                console.log('Bloqueo producer proccess action');
                                console.log(inCmd);
                                console.log(inVal);
                                //var id = gapi.hangout.getLocalParticipantId();
                               // var cadena = objMessage["usrID"];
                                //cadena=cadena.replace(/:/g,"");
                                //console.log(cadena);
                                // Get the default video feed.
                                //var feed = gapi.hangout.layout.getDefaultVideoFeed();

                                // Set the local participant to be sticky.
                                // Note that this will close any main area app.
                                //feed.setDisplayedParticipant(id);

                                //this.showFocus();
                                //gapi.hangout.layout.getDefaultVideoFeed().setDisplayedParticipant(cadena);
                                //ProStudioApp.prototype.processHostAction(theCommand, useThisID);
                                break;
                            case "MsgMute":
                                gapi.hangout.av.setMicrophoneMute(true);
                                window.lockMute = true;
                                break;
                            case "MsgUnMute":
                                window.lockMute = false;
                                gapi.hangout.av.setMicrophoneMute(false);
                                break;
                            case "CamMute":
                                if(!window.MuteOverlay.isVisible()){
                                    window.MuteOverlay.setVisible(true);
                                }
                                if(window.LogoOverlay.isVisible()){
                                    window.LogoOverlay.setVisible(false);
                                }
                                break;
                            case "CamUnMute":
                                if(window.MuteOverlay.isVisible()){
                                    window.MuteOverlay.setVisible(false);
                                }
                                break;
                            case "LogoShow":
                                if(!window.LogoOverlay.isVisible()){
                                    window.LogoOverlay.setVisible(true);
                                }
                                if(window.MuteOverlay.isVisible()){
                                    window.MuteOverlay.setVisible(false);
                                }
                                break;
                            case "LogoHide":
                                if(window.LogoOverlay.isVisible()){
                                    window.LogoOverlay.setVisible(false);
                                }
                                break;
                            case "MsgBanz":
                                ProStudioApp.prototype.executeBanish();
                                break;
                            default:
//                                console.log("Unhandled processAction: " + inID);
                            //    doContinue = false;
                                break;
                        }
                        // Make sure to add the MessageID to the array of received MessageIDs
                        window.arrMessages[window.arrMessages.length] = objMessage["msgID"];
                    }
                }
            }
        }
        if(((window.isBroadcaster==true)||(ProStudioApp.prototype.isHost(window.myParticipantID)))&&(inCmd=="MsgMute")){
            ProStudioApp.prototype.processHostAction(inCmd, inVal);
        }
// if(debug==true){console.log("     processAction: out \n          sid:" + debugSequence++);}
    };

    ProStudioApp.prototype.executeBanish = function(){
// if(debug==true){console.log("executeBanish: in \n          sid:" + debugSequence++);}
        top.close();
        top.location.href="//www.google.com";
// if(debug==true){console.log("     executeBanish: out \n          sid:" + debugSequence++);}
    };

    ProStudioApp.prototype.requestCue = function(){
        var inID = this.id;
        var theMessage;
        switch(inID){
            case "btnClear":
                theMessage = "All Clear!";
                break;
            case "btnStandBy":
                theMessage = "Please Stand By...";
                break;
            case "btnWrapUp":
                theMessage = "Please Wrap It Up";
                break;
            default:
//                console.log("Unhandled requestCue: " + inID);
                return false;
        }
        var theIDs = ":" + window.arrSelected.join(":") + ":";
        ProStudioApp.prototype.sendMessage(theIDs, false, theMessage);
        return true;
    };


    ProStudioApp.prototype.sayStandBy = function(){
        var theIDs = ":" + window.arrSelected.join(":") + ":";
        ProStudioApp.prototype.sendMessage(theIDs, false, "Please Stand By...");
    };

    ProStudioApp.prototype.sayWrapUp = function(){
        var theIDs = ":" + window.arrSelected.join(":") + ":";
        ProStudioApp.prototype.sendMessage(theIDs, false, "Please Wrap It Up");
    };

    ProStudioApp.prototype.sayClear = function(){
        var theIDs = ":" + window.arrSelected.join(":") + ":";
        ProStudioApp.prototype.sendMessage(theIDs, false, "All Clear!");
    };

    ProStudioApp.prototype.toggleHand = function(){
// if(debug==true){console.log("toggleHand: in \n          sid:" + debugSequence++);}
        var theID = window.myParticipantID;
        var myHand = document.getElementById("img" + theID);

        if(myHand.style.display == "none"){
            myHand.style.display = "inline";
	    this.title = "Cancelar Pedido de palabra.";
	    this.value = "Cancelar Pedido";
            window.handUp = true;
        }else{
            myHand.style.display = "none";
	    this.title = "Pedir la palabra.";
	    this.value= "Pedir la palabra";
            window.handUp = false;
        }
        ProStudioApp.prototype.sendHandMessage();
        ProStudioApp.prototype.indicateProducers();
// if(debug==true){console.log("     toggleHand: out \n          sid:" + debugSequence++);}
    };

    ProStudioApp.prototype.toggleMirror = function(){
// if(debug==true){console.log("toggleMirror: in \n          sid:" + debugSequence++);}
        var nowState = gapi.hangout.av.isLocalParticipantVideoMirrored();
        var nextState = (nowState) ? false: true;
        gapi.hangout.av.setLocalParticipantVideoMirrored(nextState);
// if(debug==true){console.log("     toggleMirror: out \n          sid:" + debugSequence++);}
    };

    ProStudioApp.prototype.sendHandMessage = function(){
// if(debug==true){console.log("sendHandMessage: in \n          sid:" + debugSequence++);}
        var theID = window.myParticipantID;
        var commandMsg = (window.handUp==true)? "handOn": "handOff";
        if (window.handUp==true){
	  ProStudioApp.prototype.addPedido();
	} else {
	  ProStudioApp.prototype.removePedido();
	}  
        commandMsg+= "_" + theID;
        gapi.hangout.data.sendMessage(commandMsg);
// if(debug==true){console.log("     sendHandMessage: out \n          sid:" + debugSequence++);}
    };

    ProStudioApp.prototype.sendScript = function(){
// if(debug==true){console.log("sendScript: in \n          sid:" + debugSequence++);}
        var theIDs = ":" + window.arrSelected.join(":") + ":";
        var scriptField = document.getElementById("txtScript");
        var scriptMsg = scriptField.value;
        scriptField.value = "";
        scriptField.focus();
        ProStudioApp.prototype.sendMessage(theIDs, true, scriptMsg);
// if(debug==true){console.log("     sendScript: out \n          sid:" + debugSequence++);}
    };

    ProStudioApp.prototype.showMessage = function(){
// if(debug==true){console.log("showMessage: in \n          sid:" + debugSequence++);}
        var theMsg = gapi.hangout.data.getValue("MsgMsg");
        if(theMsg != undefined){
            var objMessage = JSON.parse(theMsg);
            if(objMessage["msgID"]){
                if((window.arrMessages.indexOf(objMessage["msgID"])<0)&&((objMessage["usrID"]=="all")||(objMessage["usrID"].indexOf(window.myParticipantID)>=0))){
                    gapi.hangout.layout.displayNotice(objMessage["msgTxt"], objMessage["persists"]);
                    // Make sure to add the MessageID to the array of received MessageIDs
                    window.arrMessages[window.arrMessages.length] = objMessage["msgID"];
                }
            }
        }
// if(debug==true){console.log("     showMessage: out \n          sid:" + debugSequence++);}
    };

    ProStudioApp.prototype.sendMessage = function(usrIDs, persists, msgTxt){
// if(debug==true){console.log("sendMessage: in \n          sid:" + debugSequence++);}
        var d = new Date();
        var theTime = d.getTime();
        var msgID = "msg" + window.myParticipantID.substr(-5) + ":" + theTime.toString().substr(-7);
        var thisMsg = {"msgID" : msgID, "usrID": usrIDs, "persists": persists, "msgTxt": msgTxt};
        var tstThisMsg = JSON.stringify(thisMsg);
        gapi.hangout.data.setValue("MsgMsg", tstThisMsg);
// if(debug==true){console.log("     sendMessage: out \n          sid:" + debugSequence++);}
    };

    ProStudioApp.prototype.drawHandmsg = function(inID, inStatus){
// if(debug==true){console.log("drawHandmsg: in \n          sid:" + debugSequence++);}
        if(inID.length>5){
            document.getElementById("img" + inID).style.display = inStatus;
	    if (inStatus == "none" && inID == window.myParticipantID) {
	       document.getElementById("btnRaiseHand").value = "Pedir la palabra";
	    }
        }
// if(debug==true){console.log("     drawHandmsg: out \n          sid:" + debugSequence++);}
    };

    ProStudioApp.prototype.showFocus = function(){
// if(debug==true){console.log("showFocus: in \n          sid:" + debugSequence++);}
        if(window.isOnAir==true){
            var thisImg, thisID, thisImgID, thisSrc;
            var focusParticipantID;
            if(window.isBroadcaster==true){
                var newFocus = gapi.hangout.onair.getDisplayedParticipantInBroadcast();
                focusParticipantID = newFocus.split("^")[1];
                var oldFocus = gapi.hangout.data.getValue("focusParticipantID");
                if(oldFocus!=focusParticipantID){
                    gapi.hangout.data.setValue("focusParticipantID", focusParticipantID);
                }
            }else{
                focusParticipantID = gapi.hangout.data.getValue("focusParticipantID");
            }
            var allParticipants = gapi.hangout.getParticipants();
            for(var i = 0; i < allParticipants.length; i++){
                if((allParticipants[i].person)&&(allParticipants[i].person.displayName.indexOf("Broadcasting Service")<0)){
                    thisID = allParticipants[i].id.split("^")[1];
                    thisImgID = "onImg" + thisID;
                    thisImg = document.getElementById(thisImgID);
                    if(thisID.indexOf(focusParticipantID)>=0){
                        thisSrc = window.onBallPath;
                    }else{
                        thisSrc = window.offBallPath;
                    }
                    thisImg.setAttribute("src", thisSrc);
                }
            }
        }
// if(debug==true){console.log("     showFocus: out \n          sid:" + debugSequence++);}
    };

    ProStudioApp.prototype.getTopics = function(){
// if(debug==true){console.log("getTopics: in \n          sid:" + debugSequence++);}
        var topics = gapi.hangout.data.getValue("Topics");
        var arrTopics = new Array();
        if((topics != undefined&&(topics.length>0))){
            arrTopics = topics.split("**");
        }
// if(debug==true){console.log("     getTopics: out \n          sid:" + debugSequence++);}
        return(arrTopics);
    };

    ProStudioApp.prototype.getPedidos = function(){
        var pedidos = gapi.hangout.data.getValue("Pedidos");
        var arrPedidos = new Array();
        if((pedidos != undefined&&(pedidos.length>0))){
            arrPedidos = pedidos.split("**");
        }
        return(arrPedidos);
    };
    ProStudioApp.prototype.removePedidoOtro = function(){
      var arrPedidos = ProStudioApp.prototype.getPedidos();
      var itemID = this.id;
      var thisSelID;
      if(itemID.length>0){
	var oldID = itemID.substr(2).valueOf();
	if (arrPedidos[oldID].split("^")[1] == window.myParticipantID ) {
	  //Bajar mi mano.
	  document.getElementById("btnRaiseHand").click();
	} else {
	  var newArrPedidos = new Array();
	  
	  for(var i=0; i<arrPedidos.length; i++){
	    if(i != oldID){
	      newArrPedidos[newArrPedidos.length] = arrPedidos[i];
	    } else {
	      var idPedidoOld = arrPedidos[i].split("^")[1];
	      var commandMsg = "handOff";
	      commandMsg+= "_" + idPedidoOld;
	      gapi.hangout.data.sendMessage(commandMsg);
	      if ( document.getElementById("img" + idPedidoOld) != null ) {
		document.getElementById("img" + idPedidoOld).style.display = "none";
	      }
	    }
	  }
	  newPedido = newArrPedidos.join("**");
	  gapi.hangout.data.setValue("Pedidos", newPedido);
	}
	
      };
    }
    ProStudioApp.prototype.darLaPalabra = function(){
      var arrPedidos = ProStudioApp.prototype.getPedidos();
      var itemID = this.id;
      var thisSelID;
      if(itemID.length>0){
	var oldID = itemID.substr(3).valueOf();
        var idParticipanteFocoCamara = arrPedidos[oldID];
	if (arrPedidos[oldID].split("^")[1] == window.myParticipantID ) {
	  //Bajar mi mano.
	  document.getElementById("btnRaiseHand").click();
	} else {
	  var newArrPedidos = new Array();
	  
	  for(var i=0; i<arrPedidos.length; i++){
	    if(i != oldID){
	      newArrPedidos[newArrPedidos.length]= arrPedidos[i];
	    } else {
	      var idPedidoOld = arrPedidos[i].split("^")[1];
	      var commandMsg = "handOff";
	      commandMsg+= "_" + idPedidoOld;
	      gapi.hangout.data.sendMessage(commandMsg);
	      document.getElementById("img" + idPedidoOld).style.display = "none";
	    }
	  }
	  newPedido = newArrPedidos.join("**");
	  gapi.hangout.data.setValue("Pedidos", newPedido);
	}
	
	//mute a todos excepto al participante seleccionado
	var chkBoxes = document.getElementsByTagName("input");
        var arrTheseIDs = new Array();
        var arrUnMuteId = new Array();
        var thisValue;
        for(var i = 0; i < chkBoxes.length; i++) {
            if((chkBoxes[i].id.substr(0,4)=="chkP")){
              thisValue = chkBoxes[i].value; 
	      if (arrPedidos[oldID].split("^")[1] != thisValue) { 
                if(arrTheseIDs.indexOf(thisValue)<0){
                    arrTheseIDs[arrTheseIDs.length] = thisValue;
                }
	      } else { 
                if(arrUnMuteId.indexOf(thisValue)<0){
                    arrUnMuteId[arrUnMuteId.length] = thisValue;
                }
	      }
	    }
        }
        if(arrTheseIDs.length<0){
            arrTheseIDs[arrTheseIDs.length] = "none";
        }
        if(arrUnMuteId.length<0){
            arrTheseIDs[arrUnMuteId.length] = "none";
        }
        
	
	var d = new Date();
	var theTime = d.getTime();
	var theCommand = "MsgMute";
	var msgID = theCommand + window.myParticipantID.substr(-5) + ":" + theTime.toString().substr(-7);
	var arrUserIDs = arrTheseIDs;
	
	
	var useThisID = ":" + arrUserIDs.join(":") + ":";
	var thisMuteReq = {"msgID" : msgID, "usrID": useThisID};
	var tstThisMsg = JSON.stringify(thisMuteReq);
	gapi.hangout.data.setValue(theCommand, tstThisMsg);
	
	//unmute al participante seleccionado.
	theCommand = "MsgUnMute";
	msgID = theCommand + window.myParticipantID.substr(-5) + ":" + theTime.toString().substr(-7);
	arrUserIDs = arrUnMuteId;
	
	
	useThisID = ":" + arrUserIDs.join(":") + ":";
	thisMuteReq = {"msgID" : msgID, "usrID": useThisID};
	tstThisMsg = JSON.stringify(thisMuteReq);
	gapi.hangout.data.setValue(theCommand, tstThisMsg);
	
	gapi.hangout.data.setValue("DarLaPalabra", idParticipanteFocoCamara);
	gapi.hangout.data.setValue("TieneLaPalabraID", idParticipanteFocoCamara);
	
      };
    }
    ProStudioApp.prototype.moveTopic = function(){
// if(debug==true){console.log("moveTopic: in \n          sid:" + debugSequence++);}
        var itemID = this.id;
        if(itemID.length>0){
            var moveType = itemID.substr(0,2);
            var oldID = itemID.substr(2).valueOf();
            var arrTopics = ProStudioApp.prototype.getTopics();
            var currentTopicID = gapi.hangout.data.getValue("CurTopicID");
            if(moveType=="rm"){
                arrTopics.splice(oldID,1);
                if(currentTopicID>=arrTopics.length){
                    currentTopicID = parseInt(currentTopicID) - 1;
                    gapi.hangout.data.setValue("CurTopicID", currentTopicID.toString());
                }
            }else{
                var newID = (moveType=="up")? oldID--: oldID++;
                var theBuffer = arrTopics[newID];
                arrTopics[newID] = arrTopics[oldID];
                arrTopics[oldID] = theBuffer;
                if(currentTopicID>=arrTopics.length){
                    currentTopicID = newID;
                    gapi.hangout.data.setValue("CurTopicID", currentTopicID);
                }
            }
            var theReturn = arrTopics.join("**");
            gapi.hangout.data.setValue("Topics", theReturn);
        }
// if(debug==true){console.log("     moveTopic: out \n          sid:" + debugSequence++);}
    };

    ProStudioApp.prototype.addTopic = function(){
// if(debug==true){console.log("addTopic: in \n          sid:" + debugSequence++);}
        var arrTopics = ProStudioApp.prototype.getTopics();
        var newTopic = document.getElementById("txtAddTopic").value;
        arrTopics[arrTopics.length] = newTopic;
        newTopic = arrTopics.join("**");
        gapi.hangout.data.setValue("Topics", newTopic);
// if(debug==true){console.log("     addTopic: out \n          sid:" + debugSequence++);}
    };

    ProStudioApp.prototype.addPedido = function(){
        var arrPedidos = ProStudioApp.prototype.getPedidos();
        var newPedido = gapi.hangout.getLocalParticipantId();
        arrPedidos[arrPedidos.length] = newPedido;
        newPedido = arrPedidos.join("**");
        gapi.hangout.data.setValue("Pedidos", newPedido);
    };
    ProStudioApp.prototype.removePedido = function(){
        var arrPedidos = ProStudioApp.prototype.getPedidos();
	var newArrPedidos = new Array();
        var newPedido = gapi.hangout.getLocalParticipantId();
	
	for(var i=0; i<arrPedidos.length; i++){
	  thisSelID = arrPedidos[i];
	  if(newPedido != thisSelID){
	    newArrPedidos[newArrPedidos.length]=thisSelID; 
	  }
        }
	
        newPedido = newArrPedidos.join("**");
        gapi.hangout.data.setValue("Pedidos", newPedido);
    };


    ProStudioApp.prototype.setTopic = function(){
// if(debug==true){console.log("setTopic: in \n          sid:" + debugSequence++);}
        var itemID = this.id;
        if(itemID.length>0){
            var theID = itemID.substr(3).valueOf();
            gapi.hangout.data.setValue("CurTopicID", theID);
        }
// if(debug==true){console.log("setTopic: out \n          sid:" + debugSequence++);}
    };

    ProStudioApp.prototype.nextTopic = function(){
// if(debug==true){console.log("nextTopic: in \n          sid:" + debugSequence++);}
        var arrTopics = ProStudioApp.prototype.getTopics();
        var currentTopicID = gapi.hangout.data.getValue("CurTopicID");
        if(currentTopicID==undefined){
            theID = -1;
        }else{
            theID = parseInt(currentTopicID);
        }
        if(arrTopics.length>theID+1){
            theID++;
        }
        theID = theID.toString();
        gapi.hangout.data.setValue("CurTopicID", theID);
// if(debug==true){console.log("nextTopic: out \n          sid:" + debugSequence++);}
    };

    ProStudioApp.prototype.prevTopic = function(){
// if(debug==true){console.log("prevTopic: in \n          sid:" + debugSequence++);}
        var currentTopicID = gapi.hangout.data.getValue("CurTopicID");
        if(currentTopicID==undefined){
            theID = -1;
        }else{
            theID = parseInt(currentTopicID);
        }
        if(theID>0){
            theID--;
        }
        theID = theID.toString();
        gapi.hangout.data.setValue("CurTopicID", theID);
// if(debug==true){console.log("prevTopic: out \n          sid:" + debugSequence++);}
    };

    ProStudioApp.prototype.getProducers = function(){
// if(debug==true){console.log("getProducers: in \n          sid:" + debugSequence++);}
        var producers = gapi.hangout.data.getValue("Producers");
        if(producers == undefined){
            producers = ":" + gapi.hangout.data.getValue("HostID") + ":";
        }
// if(debug==true){console.log("getProducers: out \n          sid:" + debugSequence++);}
        return(producers);
    };

    ProStudioApp.prototype.setProducers = function(){
// if(debug==true){console.log("setProducers: in \n          sid:" + debugSequence++);}
        //Sets each ID stored in arrSelected to be a producer, and always includes the Host
        console.log('SETPRODUCER');
        var hostID = ProStudioApp.prototype.getHostID();
        var theProducers = gapi.hangout.data.getValue("Producers");
        var arrSelectedIDs = window.arrSelected;
        var thisSelID;
        //console.log(hostID);
        if(!theProducers){theProducers = '';}
        var inID = this.id;
        console.log(inID);
        switch(inID){
            case "btnSetProducer":
                for(var i=0; i<arrSelectedIDs.length; i++){
                    thisSelID = arrSelectedIDs[i];
                    if(theProducers.indexOf(thisSelID)<0){
                        theProducers += thisSelID + ":";
                    }
                }
                break;
            case "btnRevokeProducer":
                for(var j=0; j<arrSelectedIDs.length; j++){
                    thisSelID = arrSelectedIDs[j] + ":";
                    theProducers = theProducers.replace(thisSelID, "");
                }
                break;
        }
        if(theProducers.indexOf(hostID)<0){
            theProducers += hostID + ":";
        }        gapi.hangout.data.setValue("Producers", theProducers);
// if(debug==true){console.log("     setProducers: out \n          sid:" + debugSequence++);}
    };

    ProStudioApp.prototype.isProducer = function(theID, producers){
// if(debug==true){console.log("isProducer: in \n          sid:" + debugSequence++);}
        //Determine if the provided user is a designated Producer
        theReturn = (producers.indexOf(theID)>=0);
// if(debug==true){console.log("     isProducer: out \n          sid:" + debugSequence++);}
        return theReturn;
    };

    ProStudioApp.prototype.getHostID = function(){
// if(debug==true){console.log("getHostID: in \n          sid:" + debugSequence++);}
        var hostID = gapi.hangout.data.getValue("HostID");
        if(hostID == undefined){
            if(window.isOnAir==false){
                hostID = window.myParticipantID;
                gapi.hangout.data.setValue("HostID", hostID);
                gapi.hangout.data.setValue("Producers", ":" + hostID + ":");
            }else{
                hostID = "0";
            }
        }
// if(debug==true){console.log("     getHostID: out \n          sid:" + debugSequence++);}
        return(hostID);
    };

    ProStudioApp.prototype.isHost = function(inID){
// if(debug==true){console.log("isHost: in \n          sid:" + debugSequence++);}
        //Determine if the provided user is the Host of the Hangout
        var hostID = ProStudioApp.prototype.getHostID();
// if(debug==true){console.log("     isHost: out HostID: " + hostID + " \n          sid:" + debugSequence++);}
        return (hostID.indexOf(inID)>=0);
    };

    ProStudioApp.prototype.indicateProducers = function(){
// if(debug==true){console.log("indicateProducers: in \n          sid:" + debugSequence++);}
        //Loop through participant list and mark as Hosts, Producers, Users or Non-Users as appropriate
        var producers = ProStudioApp.prototype.getProducers();
        var theLI, thisID;
        var allParticipants = gapi.hangout.getParticipants();
        var hostID = ProStudioApp.prototype.getHostID();
        var noHost = true;

        var appUsers = gapi.hangout.getEnabledParticipants();
        var arrEnabledIDs = new Array();

        for(var h = 0; h < appUsers.length; h++){
            arrEnabledIDs[arrEnabledIDs.length] = appUsers[h].id.split("^")[1];
        }

        for(var i = 0; i < allParticipants.length; i++){
            if((allParticipants[i].person)&&(allParticipants[i].person.displayName.indexOf("Broadcasting Service")<0)){
                thisID = allParticipants[i].id.split("^")[1];
                theLI = document.getElementById("li" + thisID);
                if((allParticipants[i].hasAppEnabled==true)||(arrEnabledIDs.indexOf(thisID)>=0)){
                    if(hostID.indexOf(thisID)>=0){
                        theLI.className = "host";
                        theLI.title = "Productor Principal: Es la persona que creo el hangout.";
                        noHost = false;
                    }else{
                        if(producers.indexOf(thisID)>=0){
                            theLI.className = "producer";
                            theLI.title = "Productor: Esta persona puede enviar mensajes y utilizar las herramientas con otros participantes de Hangouts moderadas.";
                        }else{
                            theLI.className = "goodTarget";
                            theLI.title = "Participante: Esta persona esta utilizando Hangouts Moderadas y esta sujeto a que le apliquen las acciones ejecutadas por el productor de la conferencia.";
                        }
                    }
                    if (thisID == window.tieneLaPalabraID.split("^")[1] ) {
                            theLI.className = theLI.className + " locutor";
		    }
		      
                }else{
                    theLI.className = "unknown";
                    theLI.title = "Desconocido: esta persona no esta utilizando Hangouts Moderadas. Solicitarle que instale la extension.";
                }
            }
        }
        if(noHost==true){
            ProStudioApp.prototype.electHost();
        }
// if(debug==true){console.log("     indicateProducers: out \n          sid:" + debugSequence++);}
    };

//Return the instance
    return new ProStudioApp();
})(window || {})